import { GoogleOneTapClient } from '../../oneTap/GoogleOneTapClient.mjs';
import { loadGoogleOneTapClient } from '../../oneTap/OneTapProvider.mjs';
import { StytchAPIError } from '../../../../core/src/public/SDKErrors.mjs';

const DefaultDynamicConfig = Promise.resolve({
    pkceRequiredForOAuth: false
});
/**
 * Handles loading One Tap config from Stytch API and initializing {@link GoogleOneTapClient}
 */ class B2BOneTapProvider {
    _networkClient;
    _pkceManager;
    _config;
    googleClientID;
    constructor(_networkClient, _pkceManager, _config = DefaultDynamicConfig){
        this._networkClient = _networkClient;
        this._pkceManager = _pkceManager;
        this._config = _config;
    }
    async fetchGoogleStart() {
        if (this.googleClientID) {
            return this.googleClientID;
        }
        const oneTapStartResp = await this._networkClient.fetchSDK({
            url: '/b2b/oauth/google/onetap/start',
            method: 'GET'
        });
        this.googleClientID = oneTapStartResp.google_client_id;
        return this.googleClientID;
    }
    async submitGoogleOneTapTokenDiscovery({ credential, discoveryRedirectUrl }) {
        let codeChallenge = undefined;
        const { pkceRequiredForOAuth } = await this._config;
        if (pkceRequiredForOAuth) {
            const keyPair = await this._pkceManager.startPKCETransaction();
            codeChallenge = keyPair.code_challenge;
        } else {
            this._pkceManager.clearPKPair();
        }
        return await this._networkClient.fetchSDK({
            url: '/b2b/oauth/google/onetap/discovery/submit',
            method: 'POST',
            body: {
                id_token: credential,
                discovery_redirect_url: discoveryRedirectUrl,
                pkce_code_challenge: codeChallenge
            }
        });
    }
    async submitGoogleOneTapToken({ credential, organizationId, signupRedirectUrl, loginRedirectUrl }) {
        let codeChallenge = undefined;
        const { pkceRequiredForOAuth } = await this._config;
        if (pkceRequiredForOAuth) {
            const keyPair = await this._pkceManager.startPKCETransaction();
            codeChallenge = keyPair.code_challenge;
        } else {
            this._pkceManager.clearPKPair();
        }
        return await this._networkClient.fetchSDK({
            url: '/b2b/oauth/google/onetap/submit',
            method: 'POST',
            body: {
                id_token: credential,
                organization_id: organizationId,
                signup_redirect_url: signupRedirectUrl,
                login_redirect_url: loginRedirectUrl,
                pkce_code_challenge: codeChallenge
            }
        });
    }
    async createOneTapClient() {
        let googleClientId;
        try {
            googleClientId = await this.fetchGoogleStart();
        } catch (e) {
            const err = StytchAPIError.from(e);
            return {
                success: false,
                reason: err.error_type
            };
        }
        if (googleClientId === '') {
            return {
                success: false,
                reason: 'oauth_config_not_found'
            };
        }
        const client = new GoogleOneTapClient(await loadGoogleOneTapClient(), googleClientId);
        return {
            success: true,
            client
        };
    }
    createOnDiscoverySuccessHandler = ({ discoveryRedirectUrl, onSuccess, onError })=>async (response)=>{
            const { credential } = response;
            let submitPromise = this.submitGoogleOneTapTokenDiscovery({
                credential,
                discoveryRedirectUrl
            }).then((result)=>onSuccess(result.redirect_url));
            if (onError) {
                submitPromise = submitPromise.catch((error)=>onError(error));
            }
            await submitPromise;
        };
    createOnSuccessHandler = ({ organizationId, signupRedirectUrl, loginRedirectUrl, onSuccess, onError })=>async (response)=>{
            const { credential } = response;
            let submitPromise = this.submitGoogleOneTapToken({
                credential,
                organizationId,
                signupRedirectUrl,
                loginRedirectUrl
            }).then((result)=>onSuccess(result.redirect_url));
            if (onError) {
                submitPromise = submitPromise.catch((error)=>onError(error));
            }
            await submitPromise;
        };
    redirectOnSuccess = (redirect_url)=>{
        window.location.href = redirect_url;
    };
}

export { B2BOneTapProvider };
//# sourceMappingURL=B2BOneTapProvider.mjs.map
