'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var client = require('@dynamic-labs-sdk/client');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var utils = require('@dynamic-labs/utils');
require('@dynamic-labs-sdk/client/core');
require('eventemitter3');
require('../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
var ViewContext = require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
var hasPendingMfaAction = require('../../../shared/utils/functions/hasPendingMfaAction/hasPendingMfaAction.cjs');
var instrumentAuthLoginFailed = require('../../../shared/utils/functions/instrumentAuthLoginFailed/instrumentAuthLoginFailed.cjs');
require('../../../shared/consts/index.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-wallet/browser-wallet-client');
require('@dynamic-labs/locale');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');
require('../../../events/dynamicEvents.cjs');
var storeTokenAndUser = require('../../../client/extension/storeTokenAndUser/storeTokenAndUser.cjs');
var useProjectSettings = require('../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.cjs');
var AccessDeniedContext = require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
var AccountExistsContext = require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var ErrorContext = require('../../../context/ErrorContext/ErrorContext.cjs');
var LoadingContext = require('../../../context/LoadingContext/LoadingContext.cjs');
var useEmbeddedWallet = require('../useEmbeddedWallet/useEmbeddedWallet.cjs');
require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../functions/compareChains/compareChains.cjs');
require('../../../context/VerificationContext/VerificationContext.cjs');
require('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
var useHandleAuthenticatedUser = require('../useHandleAuthenticatedUser/useHandleAuthenticatedUser.cjs');

const sleepToShowSuccessMessage = () => utils.sleep(1500);
const useUserAuth = ({ authMethod, }) => {
    const { handleLogOutWithReason, setShowAuthFlow, setCallback, setMultiWalletWidgetState, walletConnectorOptions, } = useInternalDynamicContext.useInternalDynamicContext();
    const { setDeniedOauthUsername, setDeniedOauthProvider } = AccessDeniedContext.useAccessDeniedContext();
    const { view, pushView, clearStackAndPushInitialView } = ViewContext.useViewContext();
    const { setLoading } = LoadingContext.useLoadingContext();
    const { setErrorMessage, setError } = ErrorContext.useErrorContext();
    const { setExistentAccountData } = AccountExistsContext.useAccountExistsContext();
    const handleAuthenticatedUser = useHandleAuthenticatedUser.useHandleAuthenticatedUser();
    const { shouldAutoCreateEmbeddedWallet, shouldPromptForKeyExport, embeddedWalletSettingVersion, } = useEmbeddedWallet.useEmbeddedWallet();
    const projectSettings = useProjectSettings.useProjectSettings();
    const isVerifyResponse = (response) => response.user;
    const cancelAuth = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        logger.logger.debug('cancelAuth', { authMethod });
        yield handleLogOutWithReason('auth-cancelled');
        clearStackAndPushInitialView();
    }), [authMethod, clearStackAndPushInitialView, handleLogOutWithReason]);
    const handleAuthError = React.useCallback((error, { options = {}, onError, }) => {
        var _a, _b;
        instrumentAuthLoginFailed.instrumentAuthLoginFailed(error, {
            authOrigin: 'user-auth',
            provider: authMethod,
        });
        if (error instanceof client.MfaInvalidOtpError ||
            error instanceof client.MfaRateLimitedError) {
            throw error;
        }
        // these get caught in onboarding form and handled there
        if (error instanceof utils.EmailAlreadyExistsError ||
            error instanceof utils.CustomFieldNotUniqueError ||
            error instanceof utils.UsernameAlreadyExistsError ||
            error instanceof utils.TooManyEmailVerificationsError ||
            error instanceof utils.InvalidPhoneNumberError)
            throw error;
        if (error instanceof utils.NoAccessError) {
            setDeniedOauthProvider(error === null || error === void 0 ? void 0 : error.socialProvider);
            setDeniedOauthUsername((_a = error === null || error === void 0 ? void 0 : error.socialUsername) !== null && _a !== void 0 ? _a : '');
            pushView('no-access');
            return;
        }
        if (error instanceof utils.AccountExistsError) {
            setExistentAccountData(error.errorPayload);
            pushView('account-exists');
            return;
        }
        if (error instanceof utils.SandboxMaximumThresholdReachedError ||
            error instanceof client.SandboxMaximumThresholdReachedError) {
            pushView('sandbox-maximum-threshold-reached');
            return;
        }
        // Handle the case where the user has already an account with the email
        if (error instanceof utils.UserHasAccountWithEmailError) {
            pushView('merge-user-accounts-with-same-email', {
                returnToView: 'isEmailRecoveryFlow' in options && options.isEmailRecoveryFlow
                    ? 'passkey-recovery-add-email'
                    : undefined,
            });
            return;
        }
        // Re-throw passkey errors so they propagate to usePromise in the UI
        // This allows error messages to be displayed in ConfirmPasskeyView
        // WebAuthnError is the specific error type thrown by @simplewebauthn/browser
        // for passkey operations (authentication/registration failures)
        // NotAllowedError is the underlying DOMException when user cancels or times out
        if ((error === null || error === void 0 ? void 0 : error.name) === 'NotAllowedError' &&
            (((_b = error === null || error === void 0 ? void 0 : error.constructor) === null || _b === void 0 ? void 0 : _b.name) === 'WebAuthnError' ||
                (error === null || error === void 0 ? void 0 : error.code) === 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY')) {
            throw error;
        }
        // Re-throw passkey registration errors so they propagate to usePromise in the UI
        // InvalidStateError with ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED occurs when
        // a user tries to register a passkey that has already been registered
        if ((error === null || error === void 0 ? void 0 : error.name) === 'InvalidStateError' &&
            (error === null || error === void 0 ? void 0 : error.code) === 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED') {
            throw error;
        }
        if (error.code === utils.ErrorCode.CREDENTIAL_NOT_ENABLED_FOR_SIGN_IN) {
            setError(error.message, error.code);
            return;
        }
        if (onError) {
            onError === null || onError === void 0 ? void 0 : onError(error);
            return;
        }
        if (error.code) {
            setErrorMessage(error.code, error, 'user-auth');
        }
        else {
            setError(error.message);
        }
    }, [
        authMethod,
        pushView,
        setDeniedOauthProvider,
        setDeniedOauthUsername,
        setError,
        setErrorMessage,
        setExistentAccountData,
    ]);
    const initAuth = React.useCallback((_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ isSignIn = true, verifyFunction, onVerifySuccess, onSettled, onError, showSuccessMessage = false, skipDefaultErrorHandling = false, }) {
        var _b, _c, _d, _e, _f;
        logger.logger.debug('initAuth', { authMethod, isSignIn });
        try {
            // TODO: change this logic to const verifiedUser = await verifyFunction();
            // once all verify functions are updated to return UserProfile instead of VerifyResponse
            const verifyResponse = yield verifyFunction();
            if (!verifyResponse) {
                yield cancelAuth();
                throw new utils.DynamicError('No user returned from verify function', 'no_user_returned_from_verify_function');
            }
            let verifiedUser;
            if (isVerifyResponse(verifyResponse)) {
                verifiedUser = storeTokenAndUser.storeTokenAndUser(verifyResponse);
            }
            else {
                verifiedUser = verifyResponse;
            }
            onVerifySuccess === null || onVerifySuccess === void 0 ? void 0 : onVerifySuccess(verifiedUser);
            walletConnectorOptions.forEach((walletOption) => {
                walletOption.walletConnector.setVerifiedCredentials(verifiedUser.verifiedCredentials);
            });
            if (hasPendingMfaAction.hasPendingMfaAction(verifiedUser)) {
                // handled in SyncAuthFlow
                return;
            }
            if (isSignIn && ((_b = verifiedUser.missingFields) === null || _b === void 0 ? void 0 : _b.length)) {
                //onboarding will be handled in the onboarding flow
                return;
            }
            setMultiWalletWidgetState('idle');
            yield handleAuthenticatedUser(verifiedUser);
            // we should only close auth flow if no wallet is going to be created or there is no key export
            // otherwise there will be a glitch with auth flow closing and then reopening for passkeys or export
            const shouldCreateWallet = shouldAutoCreateEmbeddedWallet();
            // only support export prompt on v2 and higher
            const shouldPromptExport = shouldPromptForKeyExport();
            if (showSuccessMessage) {
                // this timeout is set to make sure that the user will see success message
                yield sleepToShowSuccessMessage();
            }
            if (isSignIn) {
                setCallback('authSuccess');
            }
            const walletVersion = embeddedWalletSettingVersion();
            const userHasEmbeddedWallet = (_d = (_c = verifiedUser.verifiedCredentials) === null || _c === void 0 ? void 0 : _c.some((vc) => vc.walletProvider === sdkApiCore.WalletProviderEnum.EmbeddedWallet)) !== null && _d !== void 0 ? _d : false;
            const shouldKeepAuthFlowOpenForPasswordSetup = walletVersion === sdkApiCore.EmbeddedWalletVersionEnum.V3 &&
                Boolean((_f = (_e = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _e === void 0 ? void 0 : _e.waas) === null || _f === void 0 ? void 0 : _f.passcodeRequired) &&
                !userHasEmbeddedWallet;
            if (shouldKeepAuthFlowOpenForPasswordSetup) {
                // Keep auth flow open so setup-password can be shown (useSyncDynamicWaas)
            }
            else if (walletVersion === sdkApiCore.EmbeddedWalletVersionEnum.V1 &&
                shouldCreateWallet) {
                setShowAuthFlow(true);
            }
            else if (!shouldCreateWallet || !shouldPromptExport) {
                setShowAuthFlow(false);
            }
            onSettled === null || onSettled === void 0 ? void 0 : onSettled();
        }
        catch (error) {
            logger.logger.debug(error);
            if (skipDefaultErrorHandling) {
                onError === null || onError === void 0 ? void 0 : onError(error);
                return;
            }
            handleAuthError(error, { onError });
        }
        finally {
            setLoading(false);
            onSettled === null || onSettled === void 0 ? void 0 : onSettled();
        }
    }), [
        authMethod,
        cancelAuth,
        embeddedWalletSettingVersion,
        handleAuthError,
        handleAuthenticatedUser,
        projectSettings,
        setCallback,
        setLoading,
        setMultiWalletWidgetState,
        setShowAuthFlow,
        shouldAutoCreateEmbeddedWallet,
        shouldPromptForKeyExport,
        walletConnectorOptions,
    ]);
    const handleVerifyMissingFields = React.useCallback((_g) => _tslib.__awaiter(void 0, [_g], void 0, function* ({ missingFields, isEmailVerificationRequired, isSmsVerificationRequired, }) {
        if (isEmailVerificationRequired &&
            missingFields.find((field) => field.name === 'email')) {
            pushView('verify-email');
            return;
        }
        if (isSmsVerificationRequired &&
            missingFields.find((field) => field.name === 'phoneNumber')) {
            pushView('verify-sms');
            return;
        }
        pushView(view.type);
    }), [pushView, view === null || view === void 0 ? void 0 : view.type]);
    const completeAuth = React.useCallback((_h) => _tslib.__awaiter(void 0, [_h], void 0, function* ({ completeSignInFlow, updateJwtFunction, onValidUpdatedJwt, options = {}, }) {
        logger.logger.debug('completeAuth', { authMethod });
        try {
            const { updateUserProfileResponse, isSmsVerificationRequired, isEmailVerificationRequired, missingFields, } = yield updateJwtFunction();
            onValidUpdatedJwt === null || onValidUpdatedJwt === void 0 ? void 0 : onValidUpdatedJwt();
            const updatedUser = storeTokenAndUser.storeTokenAndUser({
                expiresAt: updateUserProfileResponse.expiresAt,
                jwt: updateUserProfileResponse.jwt,
                minifiedJwt: updateUserProfileResponse.minifiedJwt,
                user: updateUserProfileResponse.user,
            });
            if (missingFields.length > 0) {
                yield handleVerifyMissingFields({
                    isEmailVerificationRequired,
                    isSmsVerificationRequired,
                    missingFields,
                });
                return;
            }
            yield handleAuthenticatedUser(updatedUser);
            setCallback('authSuccess');
            if (completeSignInFlow) {
                const shouldReturn = yield completeSignInFlow(updateUserProfileResponse);
                if (shouldReturn) {
                    return;
                }
            }
            // we should only close auth flow if no wallet is going to be created,
            // otherwise there will be a glitch with auth flow closing and then reopening for passkeys
            const shouldCreateWallet = shouldAutoCreateEmbeddedWallet();
            if (!shouldCreateWallet &&
                updatedUser.mfaBackupCodeAcknowledgement !==
                    sdkApiCore.MfaBackupCodeAcknowledgement.Pending) {
                setShowAuthFlow(false);
            }
        }
        catch (error) {
            logger.logger.debug(error);
            handleAuthError(error, { options });
        }
        finally {
            setLoading(false);
        }
    }), [
        authMethod,
        handleAuthError,
        handleAuthenticatedUser,
        handleVerifyMissingFields,
        setCallback,
        setLoading,
        setShowAuthFlow,
        shouldAutoCreateEmbeddedWallet,
    ]);
    return {
        cancelAuth,
        completeAuth,
        handleAuthError,
        initAuth,
    };
};

exports.useUserAuth = useUserAuth;
