//
//  SelfcareUtils.swift
//  
//
//  Created by TB_COWORKER on 13/06/2023.
//

import Foundation
import TrustBuilderMfaLibSwift

class SelfcareUtils {
    
    public static func authorizeInAppAuthentication(tknAlias: String) async throws -> AuthorizeResponse {
        let secureTokenListing = TrustBuilderMfaLibHolder.getLibInstance().startSecureTokensListing();
        let secureTokens = try! await secureTokenListing.execute();
        if (secureTokens.isError) {
            throw ApplicationError.SELFCARE_AUTH_ERROR(secureTokens.error!.errorMessage)
        }
        let secureToken = secureTokens.response?.filter({ $0.tknAlias == tknAlias }).first;
        
        let authParams = AuthorizationRequestParams(tknAlias: tknAlias, scope: .session);
        let authorizationRequest = try TrustBuilderMfaLibHolder.getLibInstance().startAuthorizationRequest(param: authParams)
        let authorizationResponse = try! await authorizationRequest.execute();
        if (authorizationResponse.isError) {
            if authorizationResponse.error?.errorCode == AuthorizationRequestErrors.IW_CORE_CNX_ERR {
                throw ApplicationError.IW_CORE_CNX_ERR(authorizationResponse.error!.errorMessage)
            }
            throw ApplicationError.SELFCARE_AUTH_ERROR(authorizationResponse.error!.errorMessage)
        }
        
        let inAppAuthenticationParams = InAppAuthenticationParams(tknAlias: tknAlias, sessionId: authorizationResponse.response!.sessionId, scope: .SESSION);
        let inAppAuthentication = try! TrustBuilderMfaLibHolder.getLibInstance().startInAppAuthentication(param: inAppAuthenticationParams)
        let setupResult = await inAppAuthentication.setup();
        if (setupResult.isError) {
            throw ApplicationError.SELFCARE_AUTH_ERROR(setupResult.error!.errorMessage)
        }
        let credentialProvider = setupResult.response![0];
        let authorizeResponse = AuthorizeResponse(secureToken: secureToken!, credentialProvider: credentialProvider, inAppAuthentication: inAppAuthentication)
        return authorizeResponse
    }
}
