'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { InvalidPrimaryWalletOrConnectorError, DynamicError } from '@dynamic-labs/utils';
import { isPasskeyWalletConnector } from '@dynamic-labs/wallet-connector-core';
import '@dynamic-labs/sdk-api-core';
import '@dynamic-labs-sdk/client/core';
import '../../../../client/client.js';
import 'react';
import '@dynamic-labs-sdk/client';
import '../../../../config/ApiEndpoint.js';
import '@dynamic-labs/iconic';
import 'react/jsx-runtime';
import '../../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../../../utils/constants/colors.js';
import '../../../../utils/constants/values.js';
import '../../../../shared/consts/index.js';
import { INVALID_WALLET_DATA, ERROR_PROCESSING_REVEAL_REQUEST, USER_NOT_LOGGED_IN } from '../../../../utils/constants/errors.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../../store/state/nonce/nonce.js';
import '../../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../../events/dynamicEvents.js';
import { exportEmbeddedWallet } from '../../../../data/api/embeddedWallets/embeddedWallets.js';
import '@dynamic-labs/locale';

const initExport = (_a) => __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) ||
        !isPasskeyWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
        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)
                ? 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 InvalidPrimaryWalletOrConnectorError(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 DynamicError('Something went wrong', ERROR_PROCESSING_REVEAL_REQUEST);
    }
    return turnkeyExportHandler;
});
const handleExportInitCheck = ({ user, wallet, }) => {
    var _a, _b, _c, _d, _e;
    if (!user) {
        throw new DynamicError(USER_NOT_LOGGED_IN);
    }
    if (!(wallet === null || wallet === void 0 ? void 0 : wallet.connector) ||
        !(wallet === null || wallet === void 0 ? void 0 : wallet.id) ||
        !isPasskeyWalletConnector(wallet === null || wallet === void 0 ? void 0 : wallet.connector)) {
        throw new 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 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) => __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 DynamicError('Must initialize export first', 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 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 DynamicError('Invalid export response', 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) => __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();
});

export { cleanupExport, exportCredential, extractExportBundle, initExport };
