'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var utils$1 = require('@dynamic-labs/utils');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react');
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 api = require('../api.cjs');
var utils = require('../utils.cjs');
require('@dynamic-labs-sdk/client/core');
require('eventemitter3');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-wallet/browser-wallet-client');
var constants = require('../constants.cjs');
require('@dynamic-labs/locale');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');
require('../../../events/dynamicEvents.cjs');
var storeTokenAndUser = require('../../../client/extension/storeTokenAndUser/storeTokenAndUser.cjs');
var getClientSessionNonceHeaders = require('../../../client/extension/functions/getClientSessionNonceHeaders/getClientSessionNonceHeaders.cjs');

const createTurnkeyEmbeddedWallet = (_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ attestation, challenge, environmentId, chains = [sdkApiCore.EmbeddedWalletChainEnum.Evm], passkeyAlias, sessionPublicKey, }) {
    const embeddedWallets = [
        {
            chains,
            embeddedWalletProvider: sdkApiCore.EmbeddedWalletProviderEnum.Turnkeyhd,
            isAuthenticatorAttached: false,
            passkeyAlias,
            sessionPublicKey,
        },
    ];
    if (attestation && challenge) {
        embeddedWallets[0] = Object.assign(Object.assign({}, embeddedWallets[0]), { embeddedWalletSpecificOpts: {
                attestation,
                challenge,
            }, isAuthenticatorAttached: true });
    }
    try {
        const response = yield api.sdkApi().createEmbeddedWallets({
            createEmbeddedWalletsRequest: {
                embeddedWallets,
            },
            environmentId,
        });
        return storeTokenAndUser.storeTokenAndUser(response);
    }
    catch (e) {
        yield logResponse(e, '[createTurnkeyEmbeddedWallet] Error creating embedded wallet');
        return undefined;
    }
});
const initEmbeddedWalletSession = (_b) => _tslib.__awaiter(void 0, [_b], void 0, function* ({ authenticatorType, walletId, publicKey, environmentId, }) {
    if (authenticatorType === 'passkey') {
        return api.sdkApi().initPasskeyRecovery({
            environmentId,
            initPasskeyRecoveryRequest: {
                turnkeyRecoveryTargetPublicKey: publicKey,
                walletId,
            },
        });
    }
    return api.sdkApi().initEmailAuth({
        environmentId,
        initEmailAuthRequest: {
            turnkeyEmailAuthTargetPublicKey: publicKey,
            walletId,
        },
    });
});
const completePasskeyRecovery = (_c) => _tslib.__awaiter(void 0, [_c], void 0, function* ({ walletId, attestation, challenge, environmentId, }) {
    try {
        const response = yield api.sdkApi().completePasskeyRecovery({
            completePasskeyRecoveryRequest: {
                attestation,
                challenge,
                walletId,
            },
            environmentId,
        });
        return storeTokenAndUser.storeTokenAndUser(response);
    }
    catch (e) {
        yield logResponse(e, 'Error completing passkey recovery');
        return undefined;
    }
});
const updatePasskeyRecoveryEmail = (_d) => _tslib.__awaiter(void 0, [_d], void 0, function* ({ environmentId, updateRecoveryEmailRequest, }) {
    try {
        yield api.sdkApi().updateEmbeddedWalletRecoveryEmail({
            environmentId,
            updateRecoveryEmailRequest,
        });
    }
    catch (e) {
        yield logResponse(e, 'Error while trying to update recovery email');
        throw new utils$1.DynamicError('Error updating recovery email', 'updating_recovery_email');
    }
});
const getUserPasskeys = (_e) => _tslib.__awaiter(void 0, [_e], void 0, function* ({ environmentId, }) {
    try {
        const data = yield api.sdkApi().getUserPasskeys({
            environmentId,
        });
        return data;
    }
    catch (e) {
        yield logResponse(e, 'Error getting user passkeys');
        return {
            count: 0,
            passkeys: [],
        };
    }
});
const updateUserPasskey = (_f) => _tslib.__awaiter(void 0, [_f], void 0, function* ({ environmentId, id, alias, }) {
    try {
        const data = yield api.sdkApi().updatePasskey({
            environmentId,
            updateUserPasskeyRequest: { alias, id },
        });
        return data;
    }
    catch (e) {
        yield logResponse(e, 'Error updating user passkeys', { alias, id });
        return undefined;
    }
});
const exportEmbeddedWallet = (_g) => _tslib.__awaiter(void 0, [_g], void 0, function* ({ environmentId, walletId, activityId, }) {
    try {
        const data = yield api.sdkApi().embeddedWalletExport({
            activityId,
            environmentId,
            walletId,
        });
        return data;
    }
    catch (e) {
        yield logResponse(e, 'Error exporting embedded wallet', {
            activityId,
            walletId,
        });
        return { exportBundle: '' };
    }
});
const registerSessionKey = (_h) => _tslib.__awaiter(void 0, [_h], void 0, function* ({ environmentId, walletId, publicKey, prevSessionKeySignature, }) {
    let response;
    try {
        const { nonce, nonceSignature, publicKey: sessionPublicKey, } = yield getClientSessionNonceHeaders.getClientSessionNonceHeaders();
        response = yield api.sdkApi({
            customHeaders: {
                [constants.DYNAMIC_SESSION_NONCE_HEADER]: nonce,
                [constants.DYNAMIC_SESSION_NONCE_SIGNATURE_HEADER]: nonceSignature,
                [constants.DYNAMIC_SESSION_PUBLIC_KEY_HEADER]: sessionPublicKey,
            },
        }).registerSessionKey({
            environmentId,
            registerSessionKeyRequest: {
                prevSessionKeySignature,
                publicKey,
                walletId,
            },
        });
    }
    catch (error) {
        if (utils.isResponseLike(error)) {
            const responseError = yield utils$1.ResponseError.fromResponse({
                cause: error,
                message: 'Error register session key',
            });
            logger.logger.error(responseError, { prevSessionKeySignature, publicKey });
            utils$1.tracing.logEvent('session-key', 'Error registering session key', utils$1.tracing.formatObject({
                prevSessionKeySignature,
                publicKey,
                walletId,
            }));
            if (utils$1.PlatformService.isNativeMobile) {
                logger.logger.instrument(utils$1.tracing.packScopes());
            }
            if (responseError.response.status === 422) {
                if (responseError.json.code ===
                    sdkApiCore.UnprocessableEntityErrorCode.InvalidSessionPublicKey) {
                    throw new utils$1.InvalidEmbeddedWalletSessionKeyError(responseError.json.error);
                }
            }
            throw responseError;
        }
        else {
            logger.logger.error(error);
        }
        throw error;
    }
    return response;
});
const getCreateEmbeddedWalletAccountRequest = (_j) => _tslib.__awaiter(void 0, [_j], void 0, function* ({ environmentId, chain, }) {
    try {
        const response = yield api.sdkApi().getCreateWalletAccountRequest({
            chain,
            environmentId,
        });
        return response;
    }
    catch (e) {
        yield logResponse(e, 'Error fetching create embedded wallet account request', { chain });
        throw new utils$1.DynamicError('Error fetching create embedded wallet account request', 'create_embedded_wallet_account_request_error');
    }
});
const createEmbeddedWalletAccount = (_k) => _tslib.__awaiter(void 0, [_k], void 0, function* ({ environmentId, createEmbeddedWalletAccountRequest, }) {
    try {
        const response = yield api.sdkApi().createWalletAccount({
            createWalletAccountRequest: {
                turnkeySignedRequest: createEmbeddedWalletAccountRequest,
            },
            environmentId,
        });
        return response;
    }
    catch (e) {
        yield logResponse(e, '[createEmbeddedWalletAccount] Error creating embedded wallet account', {
            createEmbeddedWalletAccountRequest,
        });
        throw new utils$1.DynamicError('[createEmbeddedWalletAccount] Error creating embedded wallet account', 'create_embedded_wallet_account_error');
    }
});
const getDeleteEmbeddedWalletsRequest = (_l) => _tslib.__awaiter(void 0, [_l], void 0, function* ({ environmentId, walletId, }) {
    try {
        const response = yield api.sdkApi().getEmbeddedWalletsDeleteRequest({
            environmentId,
            walletId,
        });
        return response;
    }
    catch (e) {
        yield logResponse(e, 'Error fetching delete embedded wallet request');
        throw new utils$1.DynamicError('Error fetching delete embedded wallets request', 'fetching_delete_embedded_wallets_request');
    }
});
const deleteEmbeddedWallets = (_m) => _tslib.__awaiter(void 0, [_m], void 0, function* ({ environmentId, deleteEmbeddedWalletsRequest, }) {
    try {
        const response = yield api.sdkApi().deleteEmbeddedWallets({
            deleteEmbeddedWalletsRequest: {
                turnkeySignedRequest: deleteEmbeddedWalletsRequest,
            },
            environmentId,
        });
        return response;
    }
    catch (e) {
        yield logResponse(e, 'Error deleting embedded wallets', {
            deleteEmbeddedWalletsRequest,
        });
        throw new utils$1.DynamicError('Error deleting embedded wallets', 'deleting_embedded_wallets');
    }
});
const logResponse = (error, message, data) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
    if (utils.isResponseLike(error)) {
        const responseError = yield utils$1.ResponseError.fromResponse({
            cause: error,
            message,
        });
        logger.logger.error(responseError, data);
    }
    else {
        logger.logger.error(error, data);
    }
});

exports.completePasskeyRecovery = completePasskeyRecovery;
exports.createEmbeddedWalletAccount = createEmbeddedWalletAccount;
exports.createTurnkeyEmbeddedWallet = createTurnkeyEmbeddedWallet;
exports.deleteEmbeddedWallets = deleteEmbeddedWallets;
exports.exportEmbeddedWallet = exportEmbeddedWallet;
exports.getCreateEmbeddedWalletAccountRequest = getCreateEmbeddedWalletAccountRequest;
exports.getDeleteEmbeddedWalletsRequest = getDeleteEmbeddedWalletsRequest;
exports.getUserPasskeys = getUserPasskeys;
exports.initEmbeddedWalletSession = initEmbeddedWalletSession;
exports.registerSessionKey = registerSessionKey;
exports.updatePasskeyRecoveryEmail = updatePasskeyRecoveryEmail;
exports.updateUserPasskey = updateUserPasskey;
