'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var utils = require('@dynamic-labs/utils');
require('@dynamic-labs-sdk/client/core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
var findEmbeddedWalletFromVerifiedCredentials = require('../../functions/findEmbeddedWalletFromVerifiedCredentials/findEmbeddedWalletFromVerifiedCredentials.cjs');
require('../../constants/values.cjs');
var errors = require('../../constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../constants/colors.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
require('../../../context/ViewContext/ViewContext.cjs');
require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../../shared/consts/index.cjs');
require('../../../store/state/nonce/nonce.cjs');
var updatePrimaryWalletId = require('../../functions/updatePrimaryWalletId/updatePrimaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
var primaryWalletId = require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('@dynamic-labs/locale');
var wallets = require('../../../data/api/wallets/wallets.cjs');
require('../../../events/dynamicEvents.cjs');
var storeTokenAndUser = require('../../../client/extension/storeTokenAndUser/storeTokenAndUser.cjs');
var convertSdkUserToUserProfile = require('../../../client/extension/user/convertSdkUserToUserProfile/convertSdkUserToUserProfile.cjs');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../store/state/authMode/authMode.cjs');
require('../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../functions/compareChains/compareChains.cjs');
var findPrimaryEmbeddedChain = require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var useEmbeddedWalletSessionKeys = require('../useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../context/LoadingContext/LoadingContext.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
require('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../../../context/MockContext/MockContext.cjs');
require('../../../views/CollectUserDataView/useFields.cjs');
require('../../../context/FieldsStateContext/FieldsStateContext.cjs');
require('../../../context/UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../../store/state/walletOptions/walletOptions.cjs');
require('react-i18next');
require('../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../components/Alert/Alert.cjs');
require('../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../components/IconButton/IconButton.cjs');
require('../../../components/InlineWidget/InlineWidget.cjs');
require('../../../components/Input/Input.cjs');
require('../../../components/IsBrowser/IsBrowser.cjs');
require('../../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../../components/OverlayCard/OverlayCard.cjs');
require('../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../components/Popper/Popper/Popper.cjs');
require('../../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../context/FooterAnimationContext/index.cjs');
require('../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../../context/OnrampContext/OnrampContext.cjs');
require('../../../store/state/sendBalances.cjs');
require('../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../index.cjs');
require('../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../store/state/tokenBalances.cjs');
require('../../../store/state/multichainBalances.cjs');
require('../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');

/**
 * Hook to upgrade embedded wallets
 * @returns An object containing the `upgradeEmbeddedWallet` function
 */
const useUpgradeEmbeddedWallet = () => {
    const { user, environmentId, projectSettings } = useInternalDynamicContext.useInternalDynamicContext();
    const { getSessionPublicKey, shouldRegisterSessionKeysOnSignin } = useEmbeddedWalletSessionKeys.useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    /**
     * callback to upgrade a v1 embedded wallet to v2
     * If the upgrade is successful, user is refreshed and primary wallet is updated if applicable
     *
     * @returns {Promise<void>} Resolves to void if the upgrade is successful.
     *
     * @throws {DynamicError} Throws an error if the upgrade process fails.
     *
     */
    const upgradeEmbeddedWallet = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _a, _b, _c, _d;
        if (!user)
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        const userHasV2EmbeddedWallet = user.verifiedCredentials.some((credential) => { var _a; return ((_a = credential.walletProperties) === null || _a === void 0 ? void 0 : _a.version) === sdkApiCore.EmbeddedWalletVersionEnum.V2; });
        if (userHasV2EmbeddedWallet) {
            throw new utils.DynamicError(errors.USER_HAS_V2_EMBEDDED_WALLET);
        }
        const requiredSessionKey = shouldRegisterSessionKeysOnSignin();
        if (!requiredSessionKey) {
            throw new utils.DynamicError(errors.INCOMPATIBLE_SDK_VERSION);
        }
        const sessionPublicKey = getSessionPublicKey();
        const verifyResponse = yield wallets.upgradeEmbeddedWalletToV2({
            environmentId,
            sessionPublicKey,
        });
        const newUser = verifyResponse === null || verifyResponse === void 0 ? void 0 : verifyResponse.user;
        const newUserProfile = convertSdkUserToUserProfile.convertSdkUserToUserProfile(newUser);
        const primaryWalletId$1 = primaryWalletId.getPrimaryWalletId();
        const primaryWalletExistsAfterUpgrade = (_b = (_a = newUser.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.find((vc) => vc.id === primaryWalletId$1)) === null || _b === void 0 ? void 0 : _b.id;
        if (!primaryWalletExistsAfterUpgrade) {
            const primaryEmbeddedChain = findPrimaryEmbeddedChain.findPrimaryEmbeddedChain(projectSettings);
            let targetPrimaryWalletId = (_c = findEmbeddedWalletFromVerifiedCredentials.findEmbeddedWalletFromVerifiedCredentials(newUserProfile, [primaryEmbeddedChain])) === null || _c === void 0 ? void 0 : _c.id;
            if (!targetPrimaryWalletId) {
                // Try other chains if primary chain credential was deleted during v1 to v2 upgrade
                const otherChains = Object.values(sdkApiCore.ChainEnum).filter((chain) => chain !== primaryEmbeddedChain);
                targetPrimaryWalletId = (_d = findEmbeddedWalletFromVerifiedCredentials.findEmbeddedWalletFromVerifiedCredentials(newUserProfile, otherChains)) === null || _d === void 0 ? void 0 : _d.id;
            }
            if (targetPrimaryWalletId) {
                yield updatePrimaryWalletId.updatePrimaryWalletId(targetPrimaryWalletId);
            }
        }
        /**
         * `storeTokenAndUser()` is intentionally not called within `upgradeEmbeddedWalletToV2()`.
         * Doing so would create a race condition, as invoking `storeTokenAndUser()` prematurely logs the user out.
         * This could prevent `updatePrimaryWalletId()` from executing properly, leaving the user stuck in a verification
         * process that cannot be refreshed correctly.
         */
        storeTokenAndUser.storeTokenAndUser(verifyResponse);
    }), [
        user,
        environmentId,
        projectSettings,
        getSessionPublicKey,
        shouldRegisterSessionKeysOnSignin,
    ]);
    return upgradeEmbeddedWallet;
};

exports.useUpgradeEmbeddedWallet = useUpgradeEmbeddedWallet;
