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

import UIKit
import AuthenticationServices


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
    }
    
    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
            
        }
    }
        
    func authorizationController(controller: ASAuthorizationController,
                                 didCompleteWithError error: Error) {
        print("Apple Login Error: \(error.localizedDescription)")
        complate(.failure(error))
    }
    
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return SpWindow
    }
}

