import Foundation
import CrossWebAuthKit

/// Swift wrapper between Unity and CrossWebAuthKit.
///
/// Converts ASWebAuthAdapter's async/await into an Objective-C compatible completion handler.
@MainActor
@objc public class CROSSxOAuthWrapper: NSObject {
    
    @objc public static let shared = CROSSxOAuthWrapper()
    
    private var authAdapter: ASWebAuthAdapter?
    private var currentTask: Task<Void, Never>?
    private var currentCompletion: ((URL?, Error?) -> Void)?
    
    private override init() {
        super.init()
    }
    
    /// Unity Deep Link handler (called from Bridge.mm).
    @objc public func handleDeepLinkURL(_ url: URL) {
        print("[CROSSxOAuthWrapper] Unity Deep Link received: \(url.absoluteString)")
        
        // Call the SDK's handleCallbackURL() → completes the continuation → invokes completion
        if authAdapter?.handleCallbackURL(url) == true {
            print("[CROSSxOAuthWrapper] ✅ SDK handled callback URL, continuation completed")
            // When the deep link path completes first, explicitly cancel
            // ASWebAuthenticationSession to make sure the browser is closed.
            authAdapter?.cancel()
        } else {
            print("[CROSSxOAuthWrapper] ⚠️ SDK did not handle this URL (no pending auth or scheme mismatch)")
        }
    }
    
    /// Start the OAuth flow.
    ///
    /// - Parameters:
    ///   - url: Authentication URL
    ///   - callbackScheme: Callback URL scheme
    ///   - prefersEphemeral: Whether to use an ephemeral session
    ///   - completion: Completion callback (callbackURL or error)
    @objc public func startOAuthFlow(
        url: URL,
        callbackScheme: String,
        prefersEphemeral: Bool,
        completion: @escaping (URL?, Error?) -> Void
    ) {
        print("[CROSSxOAuthWrapper] Starting OAuth flow")
        print("[CROSSxOAuthWrapper] URL: \(url.absoluteString)")
        print("[CROSSxOAuthWrapper] Callback Scheme: \(callbackScheme)")
        
        // Cancel any existing task
        currentTask?.cancel()
        currentCompletion = completion
        
        // Create a new adapter
        authAdapter = ASWebAuthAdapter(window: nil, prefersEphemeralSession: prefersEphemeral)
        
        // Wrap async/await in a Task
        currentTask = Task { @MainActor in
            do {
                print("[CROSSxOAuthWrapper] ⏳ Waiting for auth completion...")
                print("[CROSSxOAuthWrapper] SDK will call UIApplication.shared.open() on success")
                print("[CROSSxOAuthWrapper] Unity Deep Link will trigger handleCallbackURL()")
                
                guard let adapter = authAdapter else {
                    print("[CROSSxOAuthWrapper] ❌ Auth adapter is nil!")
                    completion(nil, NSError(domain: "CROSSxOAuth", code: -1, userInfo: [NSLocalizedDescriptionKey: "Auth adapter is nil"]))
                    return
                }
                
                // Call the SDK's start() → UIApplication.shared.open() → Unity Deep Link → handleCallbackURL() → completes the continuation
                let callbackURL = try await adapter.start(
                    url: url,
                    callbackScheme: callbackScheme,
                    prefersEphemeralSession: prefersEphemeral
                )
                
                print("[CROSSxOAuthWrapper] ✅ SDK completed! Callback URL: \(callbackURL.absoluteString)")
                
                // When the handleCallbackURL path completes the flow, ASWebAuthenticationSession
                // may not auto-dismiss, so explicitly clean it up.
                authAdapter?.cancel()
                authAdapter = nil
                currentTask = nil
                
                completion(callbackURL, nil)
                
            } catch {
                print("[CROSSxOAuthWrapper] ❌ Auth failed: \(error.localizedDescription)")
                
                authAdapter?.cancel()
                authAdapter = nil
                currentTask = nil
                
                completion(nil, error)
            }
        }
    }
    
    /// Cancel the OAuth flow.
    @objc public func cancelOAuthFlow() {
        print("[CROSSxOAuthWrapper] Cancelling OAuth flow")
        currentTask?.cancel()
        authAdapter?.cancel()
        authAdapter = nil
        currentTask = nil
    }
}
