'use client'
'use strict';

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

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('@dynamic-labs/sdk-api-core');
require('@dynamic-labs-sdk/client/core');
require('../../../../client/client.cjs');
require('react');
require('@dynamic-labs-sdk/client');
require('../../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
require('../../../../context/ViewContext/ViewContext.cjs');
require('../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var localStorage = require('../../../../utils/constants/localStorage.cjs');
require('../../../../utils/constants/colors.cjs');
require('../../../../utils/constants/values.cjs');
require('../../../../shared/consts/index.cjs');
var findEmbeddedWalletFromVerifiedCredentials = require('../../../../utils/functions/findEmbeddedWalletFromVerifiedCredentials/findEmbeddedWalletFromVerifiedCredentials.cjs');
var errors = require('../../../../utils/constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../../store/state/nonce/nonce.cjs');
var removeElementById = require('../../../../utils/functions/removeElementById/removeElementById.cjs');
require('../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../../events/dynamicEvents.cjs');
var embeddedWallets = require('../../../../data/api/embeddedWallets/embeddedWallets.cjs');
require('@dynamic-labs/locale');
var user = require('../../../../data/api/user/user.cjs');
var constants = require('../../PasskeyRecovery/constants.cjs');

const initEmbeddedWalletSession = (_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ authenticatorType, iframeContainer, iframeElementId, environmentId, user, wallet, sessionExpiration, }) {
    var _b;
    if (!user) {
        throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
    }
    if (!(wallet === null || wallet === void 0 ? void 0 : wallet.connector) ||
        !(wallet === null || wallet === void 0 ? void 0 : wallet.id) ||
        !walletConnectorCore.isPasskeyWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
        throw new utils.InvalidPrimaryWalletOrConnectorError();
    }
    const turnkeyRecoveryHandler = (_b = wallet.connector) === null || _b === void 0 ? void 0 : _b.getAuthenticatorHandler();
    if (authenticatorType === 'passkey' &&
        turnkeyRecoveryHandler.isSessionActive()) {
        return addNewPasskeyAuthenticator({
            environmentId,
            user,
            wallet,
        });
    }
    const publicKey = yield turnkeyRecoveryHandler.initRecovery(authenticatorType, iframeContainer, iframeElementId, sessionExpiration);
    if (!publicKey) {
        throw new utils.DynamicError('Something went wrong');
    }
    const response = yield embeddedWallets.initEmbeddedWalletSession({
        authenticatorType,
        environmentId,
        publicKey,
        walletId: wallet.id,
    });
    turnkeyRecoveryHandler.recoveryUserId =
        authenticatorType === 'passkey'
            ? response.turnkeyRecoveryUserId
            : response.turnkeyUserId;
    return;
});
const passkeyRecoveryBundleValidation = (_c) => _tslib.__awaiter(void 0, [_c], void 0, function* ({ user, bundleInput, wallet, }) {
    var _d, _e, _f, _g, _h;
    if (!bundleInput) {
        throw new utils.DynamicError('Code must be informed');
    }
    if (!(wallet === null || wallet === void 0 ? void 0 : wallet.connector) ||
        !(wallet === null || wallet === void 0 ? void 0 : wallet.id) ||
        !walletConnectorCore.isPasskeyWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
        throw new utils.InvalidPrimaryWalletOrConnectorError();
    }
    if (!user) {
        throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
    }
    const organizationId = (_g = (_f = (_e = (_d = user.verifiedCredentials) === null || _d === void 0 ? void 0 : _d.find(({ walletName, id }) => (walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey')) && id === wallet.id)) === null || _e === void 0 ? void 0 : _e.walletProperties) === null || _f === void 0 ? void 0 : _f.turnkeySubOrganizationId) !== null && _g !== void 0 ? _g : undefined;
    const turnkeyRecoveryHandler = (_h = wallet.connector) === null || _h === void 0 ? void 0 : _h.getAuthenticatorHandler();
    yield turnkeyRecoveryHandler.verifyRecoveryCode(bundleInput, organizationId);
    const sessionSettings = {
        createdAt: new Date().getTime(),
        emailCode: bundleInput,
        userId: turnkeyRecoveryHandler.recoveryUserId,
    };
    utils.StorageService.setItem(localStorage.EMBEDDED_WALLET_SESSION_SETTINGS, sessionSettings);
});
const resentRecoveryEmail = (_j) => _tslib.__awaiter(void 0, [_j], void 0, function* ({ authenticatorType, user, environmentId, wallet, }) {
    var _k;
    if (!user) {
        throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
    }
    if (!(wallet === null || wallet === void 0 ? void 0 : wallet.connector) ||
        !(wallet === null || wallet === void 0 ? void 0 : wallet.id) ||
        !walletConnectorCore.isPasskeyWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
        throw new utils.InvalidPrimaryWalletOrConnectorError();
    }
    const publicKey = (_k = wallet.connector) === null || _k === void 0 ? void 0 : _k.getAuthenticatorHandler().publicKey;
    if (!publicKey) {
        throw new utils.DynamicError('Could not proceed with your request. Please restart the process.');
    }
    return embeddedWallets.initEmbeddedWalletSession({
        authenticatorType,
        environmentId,
        publicKey,
        walletId: wallet === null || wallet === void 0 ? void 0 : wallet.id,
    });
});
const completePasskeyRecovery = (_l) => _tslib.__awaiter(void 0, [_l], void 0, function* ({ user, environmentId, wallet, }) {
    const { connector, user: updatedUser } = yield recoverTurnkeyWallet({
        addPasskeyAuthenticator: false,
        environmentId,
        user,
        wallet,
    });
    // clear iframeStamper and its reference
    connector.getAuthenticatorHandler().clear();
    // deletes iframe container after usage
    removeElementById.removeElementById(constants.iframeElementId);
    return updatedUser;
});
const addNewPasskeyAuthenticator = (_m) => _tslib.__awaiter(void 0, [_m], void 0, function* ({ user, environmentId, wallet, }) {
    const { user: updatedUser } = yield recoverTurnkeyWallet({
        addPasskeyAuthenticator: true,
        environmentId,
        user,
        wallet,
    });
    return updatedUser;
});
const recoverTurnkeyWallet = (_o) => _tslib.__awaiter(void 0, [_o], void 0, function* ({ wallet, user, environmentId, addPasskeyAuthenticator, }) {
    var _p, _q, _r;
    if (!user) {
        throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
    }
    if (!wallet ||
        !wallet.connector ||
        !wallet.id ||
        !walletConnectorCore.isPasskeyWalletConnector(wallet.connector)) {
        throw new utils.InvalidPrimaryWalletOrConnectorError();
    }
    const connector = wallet.connector;
    connector.setEmail(user.email);
    const turnkeySubOrganizationId = (_r = (_q = (_p = user.verifiedCredentials) === null || _p === void 0 ? void 0 : _p.find(({ walletName, id }) => (walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey')) && id === wallet.id)) === null || _q === void 0 ? void 0 : _q.walletProperties) === null || _r === void 0 ? void 0 : _r.turnkeySubOrganizationId;
    if (!turnkeySubOrganizationId) {
        throw new utils.DynamicError('The authentication token is invalid - turnkeySubOrganizationId is missing');
    }
    const turnkeyRecoveryHandler = wallet.connector.getAuthenticatorHandler();
    const { attestation, challenge } = yield connector.getWebAuthnAttestation();
    if (addPasskeyAuthenticator) {
        yield turnkeyRecoveryHandler.addPasskeyAuthenticator({
            attestation,
            challenge,
            turnkeySubOrganizationId,
        });
    }
    else {
        yield turnkeyRecoveryHandler.completeRecovery({
            attestation,
            challenge,
            turnkeySubOrganizationId,
        });
    }
    const updatedUser = yield embeddedWallets.completePasskeyRecovery({
        attestation: attestation,
        challenge,
        environmentId,
        walletId: wallet.id,
    });
    if (!updatedUser) {
        throw new utils.DynamicError('No user returned from passkey recovery');
    }
    const chain = connector.connectedChain;
    const embeddedWalletVerifiedCredential = findEmbeddedWalletFromVerifiedCredentials.findEmbeddedWalletFromVerifiedCredentials(updatedUser, [chain]);
    if (!embeddedWalletVerifiedCredential) {
        throw new utils.DynamicError('EmbeddedWalletVerifiedCredential not found');
    }
    connector.setVerifiedCredentials(updatedUser.verifiedCredentials);
    return {
        connector,
        user: updatedUser,
    };
});
const canRestoreEmbeddedWalletSession = (sessionExpirationTime) => {
    if (!(sessionExpirationTime === null || sessionExpirationTime === void 0 ? void 0 : sessionExpirationTime.amount)) {
        return false;
    }
    const sessionSettings = utils.StorageService.getItem(localStorage.EMBEDDED_WALLET_SESSION_SETTINGS);
    if (!sessionSettings) {
        return false;
    }
    const sessionExpiration = sessionExpirationTime.amount *
        (sessionExpirationTime.unit === 'minutes' ? 60 : 3600);
    const recoveryExpirationSeconds = (sessionSettings === null || sessionSettings === void 0 ? void 0 : sessionSettings.createdAt) + sessionExpiration * 1000;
    const expirationTime = new Date(recoveryExpirationSeconds);
    if (new Date() >= expirationTime) {
        utils.StorageService.removeItem(localStorage.EMBEDDED_WALLET_SESSION_SETTINGS);
        return false;
    }
    return true;
};
const restoreEmbeddedWalletSession = (_s) => _tslib.__awaiter(void 0, [_s], void 0, function* ({ user, iframeContainer, iframeElementId, wallet, sessionExpiration, }) {
    var _t, _u, _v, _w, _x;
    if (!user) {
        throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
    }
    if (!(wallet === null || wallet === void 0 ? void 0 : wallet.connector) ||
        !(wallet === null || wallet === void 0 ? void 0 : wallet.id) ||
        !walletConnectorCore.isPasskeyWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
        throw new utils.InvalidPrimaryWalletOrConnectorError();
    }
    const sessionSettings = utils.StorageService.getItem(localStorage.EMBEDDED_WALLET_SESSION_SETTINGS);
    const turnkeyRecoveryHandler = (_t = wallet.connector) === null || _t === void 0 ? void 0 : _t.getAuthenticatorHandler();
    if (!sessionSettings || Boolean(turnkeyRecoveryHandler.recoveryUserId)) {
        return false;
    }
    const publicKey = yield turnkeyRecoveryHandler.initRecovery('email', iframeContainer, iframeElementId, sessionExpiration);
    if (!publicKey) {
        throw new utils.DynamicError('Could not open embedded wallet connection communication');
    }
    turnkeyRecoveryHandler.recoveryUserId = sessionSettings.userId;
    const organizationId = (_x = (_w = (_v = (_u = user.verifiedCredentials) === null || _u === void 0 ? void 0 : _u.find(({ walletName, id }) => (walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey')) && id === wallet.id)) === null || _v === void 0 ? void 0 : _v.walletProperties) === null || _w === void 0 ? void 0 : _w.turnkeySubOrganizationId) !== null && _x !== void 0 ? _x : undefined;
    yield turnkeyRecoveryHandler.verifyRecoveryCode(sessionSettings.emailCode, organizationId);
    return true;
});
const addEmailRecovery = (_y) => _tslib.__awaiter(void 0, [_y], void 0, function* ({ user: user$1, environmentId, wallet, }) {
    var _z, _0;
    if (!(user$1 === null || user$1 === void 0 ? void 0 : user$1.email)) {
        throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
    }
    if (!(wallet === null || wallet === void 0 ? void 0 : wallet.connector) ||
        !(wallet === null || wallet === void 0 ? void 0 : wallet.id) ||
        !walletConnectorCore.isPasskeyWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector) ||
        !walletConnectorCore.isEmailWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
        throw new utils.InvalidPrimaryWalletOrConnectorError();
    }
    const { turnkeySubOrganizationId, turnkeyUserId } = (_0 = (_z = user$1.verifiedCredentials) === null || _z === void 0 ? void 0 : _z.find(({ walletName, id }) => (walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey')) && id === wallet.id)) === null || _0 === void 0 ? void 0 : _0.walletProperties;
    if (!turnkeySubOrganizationId || !turnkeyUserId) {
        throw new utils.DynamicError('The authentication token is invalid - turnkeySubOrganizationId or turnkeyUserID is missing');
    }
    const turnkeyRecoveryHandler = wallet.connector.getAuthenticatorHandler();
    const { signedRequest } = (yield turnkeyRecoveryHandler.addEmailRecovery({
        email: user$1.email,
        organizationId: turnkeySubOrganizationId,
        turnkeyUserId,
    }));
    yield embeddedWallets.updatePasskeyRecoveryEmail({
        environmentId,
        updateRecoveryEmailRequest: { turnkeySignedRequest: signedRequest },
    });
    wallet.connector.setEmail(user$1.email);
    return user.refreshUserJwt({ environmentId });
});

exports.addEmailRecovery = addEmailRecovery;
exports.addNewPasskeyAuthenticator = addNewPasskeyAuthenticator;
exports.canRestoreEmbeddedWalletSession = canRestoreEmbeddedWalletSession;
exports.completePasskeyRecovery = completePasskeyRecovery;
exports.initEmbeddedWalletSession = initEmbeddedWalletSession;
exports.passkeyRecoveryBundleValidation = passkeyRecoveryBundleValidation;
exports.resentRecoveryEmail = resentRecoveryEmail;
exports.restoreEmbeddedWalletSession = restoreEmbeddedWalletSession;
