//
//  SpeakEleLoginViewModel.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/17.
//

import UIKit
import AuthenticationServices
import GoogleSignIn


class SpeakEleLoginViewModel: NSObject {

    private var complate:((Result<String,Error>) ->Void) = { response in }
    
    func AppleLogin(_ onResponse:@escaping((Result<String,Error>) ->Void) ) -> Void {
        complate = onResponse
        let provider = ASAuthorizationAppleIDProvider()
        let request = provider.createRequest()
        request.requestedScopes = [.fullName, .email]
        let controller = ASAuthorizationController(authorizationRequests: [request])
        controller.delegate = self
        controller.presentationContextProvider = self
        controller.performRequests()
    }
    
    func googleLogin(_ onResponse:@escaping((Result<String,Error>) ->Void) ) -> Void {
        complate = onResponse
        GIDSignIn.sharedInstance.signIn(withPresenting: SpWindow.rootViewController ?? UIViewController()) {[weak self] result, error in
            if let error = error {
                self?.complate(.failure(error))
                return
            }
            guard let user = result?.user,
                  let userID = user.userID else {
                self?.complate(.failure(NSError(domain: "GoogleSignInError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to get user ID"])))
                return
            }
            self?.complate(.success(userID))
        }
    }
    
    func EmailLogin(_ onResponse:@escaping((Result<String,Error>) ->Void)) -> Void {
        complate = onResponse
    }
    
}

extension SpeakEleLoginViewModel : ASAuthorizationControllerDelegate , ASAuthorizationControllerPresentationContextProviding {
    
    func authorizationController(controller: ASAuthorizationController,
                                 didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            let userIdentifier = appleIDCredential.user
            _ = appleIDCredential.fullName
            _ = appleIDCredential.email
            self.complate(.success(userIdentifier))
        }
    }
        
    func authorizationController(controller: ASAuthorizationController,
                                 didCompleteWithError error: Error) {
        print("Apple Login Error: \(error.localizedDescription)")
        complate(.failure(error))
    }
    
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return SpWindow
    }
}

