'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');
var logger = require('../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../../../utils/constants/colors.cjs');
require('../../../../utils/constants/values.cjs');
require('../../../../shared/consts/index.cjs');
var errors = require('../../../../utils/constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../../store/state/nonce/nonce.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');

const initExport = (_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ iframeContainer, iframeElementId, wallet, }) {
    var _b, _c;
    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)) {
        logger.logger.error('Cannot initialize embedded wallet export', {
            connector: (_b = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _b === void 0 ? void 0 : _b.name,
            foo: (wallet === null || wallet === void 0 ? void 0 : wallet.connector)
                ? walletConnectorCore.isPasskeyWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)
                : undefined,
            version: 'v2',
            wallet: Boolean(wallet),
            walletId: wallet === null || wallet === void 0 ? void 0 : wallet.id,
        });
        throw new utils.InvalidPrimaryWalletOrConnectorError(errors.INVALID_WALLET_DATA);
    }
    const turnkeyExportHandler = (_c = wallet.connector) === null || _c === void 0 ? void 0 : _c.getExportHandler();
    const publicKey = yield turnkeyExportHandler.initExport(iframeContainer, iframeElementId);
    if (!publicKey) {
        throw new utils.DynamicError('Something went wrong', errors.ERROR_PROCESSING_REVEAL_REQUEST);
    }
    return turnkeyExportHandler;
});
const handleExportInitCheck = ({ user, wallet, }) => {
    var _a, _b, _c, _d, _e;
    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 connector = wallet.connector;
    connector.setEmail(user.email);
    const walletProperties = (_b = (_a = user.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.find(({ walletName, id }) => (walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey')) && id === wallet.id)) === null || _b === void 0 ? void 0 : _b.walletProperties;
    const turnkeyHDWalletId = (_c = walletProperties === null || walletProperties === void 0 ? void 0 : walletProperties.turnkeyHDWalletId) !== null && _c !== void 0 ? _c : undefined;
    const privateKeyId = (_d = walletProperties === null || walletProperties === void 0 ? void 0 : walletProperties.turnkeyPrivateKeyId) !== null && _d !== void 0 ? _d : undefined;
    const organizationId = (_e = walletProperties === null || walletProperties === void 0 ? void 0 : walletProperties.turnkeySubOrganizationId) !== null && _e !== void 0 ? _e : undefined;
    if (!organizationId ||
        (turnkeyHDWalletId === undefined && privateKeyId === undefined)) {
        throw new utils.DynamicError('Invalid token!');
    }
    return {
        connector,
        organizationId,
        privateKeyId,
        turnkeyHDWalletId,
    };
};
const extractExportBundle = ({ address, privateKeyId, activity, }) => {
    var _a, _b, _c;
    const exportWalletResult = address
        ? (_a = activity.result) === null || _a === void 0 ? void 0 : _a.exportWalletAccountResult
        : (_b = activity.result) === null || _b === void 0 ? void 0 : _b.exportWalletResult;
    const result = privateKeyId
        ? (_c = activity.result) === null || _c === void 0 ? void 0 : _c.exportPrivateKeyResult
        : exportWalletResult;
    return result === null || result === void 0 ? void 0 : result.exportBundle;
};
const exportCredential = (_d) => _tslib.__awaiter(void 0, [_d], void 0, function* ({ user, wallet, environmentId, address, }) {
    const { connector, turnkeyHDWalletId, privateKeyId, organizationId } = handleExportInitCheck({
        user,
        wallet,
    });
    const turnkeyExportHandler = connector.getExportHandler();
    const targetPublicKey = turnkeyExportHandler.publicKey;
    if (!targetPublicKey) {
        throw new utils.DynamicError('Must initialize export first', errors.ERROR_PROCESSING_REVEAL_REQUEST);
    }
    // calls turnkey export api
    let newActivity;
    if (turnkeyHDWalletId) {
        newActivity = yield turnkeyExportHandler.exportWallet({
            address,
            organizationId,
            walletId: turnkeyHDWalletId,
        });
    }
    else if (privateKeyId) {
        newActivity = yield turnkeyExportHandler.exportPrivateKey({
            organizationId,
            privateKeyId,
        });
    }
    const activityId = newActivity.id;
    const activityStatus = newActivity.status;
    let exportBundle;
    if (activityStatus === 'ACTIVITY_STATUS_COMPLETED') {
        exportBundle = extractExportBundle({
            activity: newActivity,
            address,
            privateKeyId,
        });
    }
    else {
        const res = yield embeddedWallets.exportEmbeddedWallet({
            activityId,
            environmentId,
            walletId: (wallet === null || wallet === void 0 ? void 0 : wallet.id) || '',
        });
        exportBundle = res === null || res === void 0 ? void 0 : res.exportBundle;
    }
    if (!exportBundle) {
        throw new utils.DynamicError('Invalid export response', errors.ERROR_PROCESSING_REVEAL_REQUEST);
    }
    if (address || privateKeyId) {
        return turnkeyExportHandler.verifyExportPrivateKey({
            chain: wallet === null || wallet === void 0 ? void 0 : wallet.chain,
            exportBundle,
            organizationId,
        });
    }
    return turnkeyExportHandler.verifyExportWallet({
        exportBundle,
        organizationId,
    });
});
const cleanupExport = (_e) => _tslib.__awaiter(void 0, [_e], void 0, function* ({ wallet }) {
    var _f;
    const connector = wallet === null || wallet === void 0 ? void 0 : wallet.connector;
    // clear iframeStamper and its reference
    (_f = connector === null || connector === void 0 ? void 0 : connector.getExportHandler()) === null || _f === void 0 ? void 0 : _f.clear();
});

exports.cleanupExport = cleanupExport;
exports.exportCredential = exportCredential;
exports.extractExportBundle = extractExportBundle;
exports.initExport = initExport;
