//
//  RNBISDKAuthorize.swift
//  RNBISDKCoreModule
//
//  Created by K Ashok on 11/03/22.
//  Copyright © 2022 BrightInsight. All rights reserved.
//

import Foundation

@objc(RNBISDKAuthorize)
class RNBISDKAuthorize: NSObject {
    
    private var api: BISDKCoreAPI?
    
    @objc(requiresMainQueueSetup)
    static func requiresMainQueueSetup() -> Bool {
        return true
    }
    
    @objc(startModule:apiKey:)
    func startModule(_ baseURL: String, apiKey: String) {
        //      let configure = BISDKConfig(baseURL: "https://api-us-dev.brightinsight.com//bi-int-rsf-nonprod-dev-rap3",apiKey: "FfpWnMOuNShHpOALZPH3gdL2mZTcCaFF")
        let configure = BISDKConfig(baseURL: baseURL,apiKey: apiKey)
        api = BISDKCoreAPI(configure);
    }
    //csl-tor-nonprod-dev-cslm => namespace for api
    //"V1RKqvGJvzgGdUHS2DAUj79TuBiuRCZj" old api key
    
    @objc(authorize:apiKey:tokenId:redirectUri:cookie:resolver:rejecter:)
    func authorize(_ baseURL: String, apiKey: String, tokenId: String, redirectUri: String, cookie: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock ) {
        print("run authorize")
        startModule(baseURL, apiKey: apiKey)
        if let api = api {
            api.authorize(
                userCookie: cookie,
                redirectUri: redirectUri,
                clientId: "oidc_pkce",
                scope: "openid biOrg biUserId biRoles",
                responseType: "code",
                state: "abc12345",
                csrf: tokenId,
                decision: "allow",
                codeChallenge: "lKrE7FUKpExIuGLo25Ab2K1t_5e3QKiYKt8M3Oedn0s",
                codeChallengeMethod: "S256",
                nonce: "12345abc") { code, statusCode in
                    print("call back in run authorize")
                    if(statusCode == 302) {
                        resolver(api.locationCode)
                    } else {
                        let error = NSError(domain: "HTTP Redirect Failed", code: statusCode, userInfo: ["": ""])
                        rejecter("","", error)
                    }
                }
        }
    }
}
