//
//  AuthorizationProgressViewController.m
//  HotPocket (iOS)
//
//  Created by Tomek Wójcik on 25/09/2025.
//

#import "AuthorizationProgressViewController.h"

#import "AppDelegate.h"
#import "HPAuthFlow.h"
#import "HPCredentialsHelper.h"
#import "MultilineLabel.h"
#import "NSBundle+HotPocketExtensions.h"

@interface AuthorizationProgressViewController (AuthorizationProgressViewControllerPrivate)

#pragma mark - Private interface

-(void)presentAuthorizationError;

@end

@implementation AuthorizationProgressViewController

#pragma mark - View lifecycle

-(instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        self.authorizationURL = nil;
        self.webAuthenticationSession = nil;
        self.userCancelledSession = NO;
    }
    
    return self;
}

-(void)viewDidLoad {
    [super viewDidLoad];
    self.progressLabel.text = NSLocalizedString(@"Continue to sign in in your browser...", @"Continue to sign in in your browser...");
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.progressIndicator startAnimating];
    
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onAuthFlowDidFinish:)
                                                 name:@"AuthFlowDidFinish"
                                               object:appDelegate.authFlow];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onAuthFlowDidReceiveAuthParams:)
                                                 name:@"AuthFlowDidReceiveAuthParams"
                                               object:appDelegate.authFlow];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    ASWebAuthenticationSessionCompletionHandler completionHandler = ^(NSURL *url, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error != nil) {
#ifdef DEBUG
                NSLog(@"[AuthorizationViewController.session completionHandler] error=`%@`", error);
#endif
                if (error.code == ASWebAuthenticationSessionErrorCodeCanceledLogin) {
                    self.userCancelledSession = YES;
                }
                [self presentAuthorizationError];
            } else {
                HPAuthParams *receivedAuthParams = [appDelegate.authFlow handlePostAuthenticateURL:url];
                if (receivedAuthParams != nil) {
                    [appDelegate.authFlow handleAuthParams:receivedAuthParams];
                } else {
                    [self presentAuthorizationError];
                }
            }
            
            self.webAuthenticationSession = nil;
        });
    };
    
    ASWebAuthenticationSessionCallback *callback = [ASWebAuthenticationSessionCallback callbackWithCustomScheme:[NSBundle postAuthenticateURLScheme]];
    self.webAuthenticationSession = [[ASWebAuthenticationSession alloc] initWithURL:self.authorizationURL
                                                                           callback:callback
                                                                  completionHandler:completionHandler];
    self.webAuthenticationSession.presentationContextProvider = self;
#ifdef DEBUG
    self.webAuthenticationSession.prefersEphemeralWebBrowserSession = YES;
#endif
    
    if (self.webAuthenticationSession.canStart == NO) {
        [self presentAuthorizationError];
        return;
    }
    
    [self.webAuthenticationSession start];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.webAuthenticationSession = nil;
    
    [self.progressIndicator stopAnimating];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

# pragma mark - Private interface

-(void)presentAuthorizationError {
    if (self.userCancelledSession == NO) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Oops!", @"Oops!")
                                                                       message:NSLocalizedString(@"HotPocket couldn't complete this operation.", @"HotPocket couldn't complete this operation.")
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Oh well", @"Oh well")
                                                  style:UIAlertActionStyleDefault
                                                handler:^(UIAlertAction *action) {
            [alert dismissViewControllerAnimated:YES completion:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }]];
        
        [self presentViewController:alert animated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - Notification handlers

-(void)onAuthFlowDidFinish:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
#ifdef DEBUG
        NSLog(@"-[AuthorizationViewController onAuthFlowDidFinish:] notification=`%@`", notification);
#endif
        HPCredentials *credentials = [[HPCredentialsHelper sharedHelper] getCredentials];
        
        if (credentials.usable == NO) {
            [self presentAuthorizationError];
        } else {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    });
}

-(void)onAuthFlowDidReceiveAuthParams:(NSNotification *)notification {
    self.progressLabel.text = NSLocalizedString(@"Processing authorization...", @"Processing authorization...");
}

# pragma mark - ASWebAuthenticationPresentationContextProviding implementation

-(ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session {
    return self.view.window;
}

@end
