#import "CROSSxOAuthBridge.h"

// Import the Swift-generated header.
// Generated by the UnityFramework module at Unity build time.
#if __has_include("UnityFramework/UnityFramework-Swift.h")
#import "UnityFramework/UnityFramework-Swift.h"
#elif __has_include("UnityFramework-Swift.h")
#import "UnityFramework-Swift.h"
#else
#error "UnityFramework-Swift.h not found. Make sure CROSSxOAuthWrapper.swift is included in UnityFramework target."
#endif

// Store callbacks
static CROSSxOAuthSuccessCallback g_successCallback = NULL;
static CROSSxOAuthErrorCallback g_errorCallback = NULL;

/// Start the OAuth flow
void CROSSxOAuth_StartFlow(
    const char* authUrl,
    const char* callbackScheme,
    int prefersEphemeral,
    CROSSxOAuthSuccessCallback onSuccess,
    CROSSxOAuthErrorCallback onError
) {
    NSLog(@"[CROSSxOAuthBridge] StartFlow called");
    
    // Store callbacks
    g_successCallback = onSuccess;
    g_errorCallback = onError;
    
    // Convert parameters
    NSString* authUrlStr = [NSString stringWithUTF8String:authUrl];
    NSString* callbackSchemeStr = [NSString stringWithUTF8String:callbackScheme];
    BOOL ephemeral = (prefersEphemeral != 0);
    
    NSURL* url = [NSURL URLWithString:authUrlStr];
    if (!url) {
        NSLog(@"[CROSSxOAuthBridge] Invalid URL: %@", authUrlStr);
        if (g_errorCallback) {
            g_errorCallback("INVALID_URL", "Invalid authentication URL");
        }
        return;
    }
    
    NSLog(@"[CROSSxOAuthBridge] URL: %@", authUrlStr);
    NSLog(@"[CROSSxOAuthBridge] Callback Scheme: %@", callbackSchemeStr);
    NSLog(@"[CROSSxOAuthBridge] Ephemeral: %d", ephemeral);
    
    // Use the Swift wrapper (runs on the main thread)
    dispatch_async(dispatch_get_main_queue(), ^{
        CROSSxOAuthWrapper* wrapper = [CROSSxOAuthWrapper shared];
        
        [wrapper startOAuthFlowWithUrl:url
                        callbackScheme:callbackSchemeStr
                     prefersEphemeral:ephemeral
                            completion:^(NSURL* _Nullable callbackURL, NSError* _Nullable error) {
            
            NSLog(@"[CROSSxOAuthBridge] Auth completed");
            
            if (error) {
                NSLog(@"[CROSSxOAuthBridge] Error: %@", error.localizedDescription);
                
                // Determine the error code
                NSString* errorCode = @"UNKNOWN_ERROR";
                if ([error.domain isEqualToString:@"com.apple.AuthenticationServices.WebAuthenticationSession"]) {
                    if (error.code == 1) {
                        errorCode = @"AUTH_CANCELLED";
                    }
                } else if ([error.localizedDescription containsString:@"cancelled"]) {
                    errorCode = @"AUTH_CANCELLED";
                }
                
                if (g_errorCallback) {
                    const char* cErrorCode = [errorCode UTF8String];
                    const char* cErrorMsg = [error.localizedDescription UTF8String];
                    g_errorCallback(cErrorCode, cErrorMsg);
                }
                return;
            }
            
            if (!callbackURL) {
                NSLog(@"[CROSSxOAuthBridge] No callback URL");
                if (g_errorCallback) {
                    g_errorCallback("INVALID_CALLBACK_URL", "Callback URL is null");
                }
                return;
            }
            
            NSLog(@"[CROSSxOAuthBridge] Callback URL: %@", callbackURL.absoluteString);
            
            // Pass the URL string directly to C#.
            // Unity C# immediately handles it via UnityDeepLinkAdapter.
            if (g_successCallback) {
                const char* urlString = [callbackURL.absoluteString UTF8String];
                NSLog(@"[CROSSxOAuthBridge] ✅ Calling C# success callback with URL");
                g_successCallback(urlString);
            }
        }];
    });
}

/// Cancel the OAuth flow
void CROSSxOAuth_CancelFlow(void) {
    NSLog(@"[CROSSxOAuthBridge] CancelFlow called");
    
    dispatch_async(dispatch_get_main_queue(), ^{
        CROSSxOAuthWrapper* wrapper = [CROSSxOAuthWrapper shared];
        [wrapper cancelOAuthFlow];
        
        g_successCallback = NULL;
        g_errorCallback = NULL;
    });
}

/// Forward a Unity Deep Link to the SDK
void CROSSxOAuth_HandleDeepLink(const char* urlCString) {
    if (!urlCString) {
        NSLog(@"[CROSSxOAuthBridge] HandleDeepLink: NULL URL");
        return;
    }
    
    NSString* urlString = [NSString stringWithUTF8String:urlCString];
    NSURL* url = [NSURL URLWithString:urlString];
    
    if (!url) {
        NSLog(@"[CROSSxOAuthBridge] HandleDeepLink: Invalid URL: %@", urlString);
        return;
    }
    
    NSLog(@"[CROSSxOAuthBridge] HandleDeepLink: %@", url.absoluteString);
    [[CROSSxOAuthWrapper shared] handleDeepLinkURL:url];
}
