'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { UnprocessableEntityErrorCode, EmbeddedWalletProviderEnum, EmbeddedWalletChainEnum } from '@dynamic-labs/sdk-api-core';
import { ResponseError, tracing, PlatformService, InvalidEmbeddedWalletSessionKeyError, DynamicError } from '@dynamic-labs/utils';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react';
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 { sdkApi } from '../api.js';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import '@dynamic-labs/locale';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../events/dynamicEvents.js';
import { storeTokenAndUser } from '../../../client/extension/storeTokenAndUser/storeTokenAndUser.js';

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

export { completePasskeyRecovery, createEmbeddedWalletAccount, createTurnkeyEmbeddedWallet, deleteEmbeddedWallets, exportEmbeddedWallet, getCreateEmbeddedWalletAccountRequest, getDeleteEmbeddedWalletsRequest, getUserPasskeys, initEmbeddedWalletSession, registerSessionKey, updatePasskeyRecoveryEmail, updateUserPasskey };
