'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { VerifyRequestFromJSON } from '@dynamic-labs/sdk-api-core';
import { DynamicError, EmbeddedWalletExistsError, WalletUsedError, MergeAccountsConfirmationError, SandboxMaximumThresholdReachedError, WalletNotDeployedError, ChainalysisError, GateBlockedError, NoAccessError, AccountExistsError } from '@dynamic-labs/utils';
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 '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '../../../context/ViewContext/ViewContext.js';
import '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../../utils/constants/colors.js';
import '../../../utils/constants/values.js';
import '../../../shared/consts/index.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import { sdkApi } from '../api.js';
import { logResponseError } from '../utils.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 storeSelectedWallet = (_a) => __awaiter(void 0, [_a], void 0, function* ({ environmentId, walletId, }) {
    try {
        const response = yield sdkApi().selectUserWallet({
            environmentId,
            userWalletSelectionRequest: {
                walletId,
            },
        });
        return storeTokenAndUser(response);
    }
    catch (e) {
        const data = yield logResponseError(e, 'Error transfering wallet');
        throw new DynamicError(data.error);
    }
});
const linkWallet = (environmentId_1, _b) => __awaiter(void 0, [environmentId_1, _b], void 0, function* (environmentId, { messageToSign, network, signedMessage, publicWalletAddress, chain, walletName, walletProvider, additionalWalletAddresses, backup, }) {
    const verifyRequest = VerifyRequestFromJSON({
        additionalWalletAddresses,
        backup,
        chain,
        messageToSign,
        network,
        publicWalletAddress,
        signedMessage,
        walletName,
        walletProvider,
    });
    try {
        const response = yield sdkApi().verifyLink({
            environmentId,
            verifyRequest,
        });
        storeTokenAndUser(response);
        return response;
    }
    catch (e) {
        const data = yield logResponseError(e, 'Error linkWallet');
        if (data.code === 'embedded_wallet_address_already_linked') {
            throw new EmbeddedWalletExistsError(data.code);
        }
        if (data.code === 'reassign_wallet_confirm' ||
            data.code === 'reassign_wallet_error') {
            throw new WalletUsedError(data.code);
        }
        if (data.code === 'merge_accounts_confirmation') {
            throw new MergeAccountsConfirmationError({
                code: data.code,
                mergeConflicts: data.payload.mergeConflicts,
                walletAddress: publicWalletAddress,
            });
        }
        if (data.error.code === 'sandbox_maximum_threshold_reached') {
            throw new SandboxMaximumThresholdReachedError(data.error.message);
        }
        throw new DynamicError(data.error);
    }
});
const unlinkWallet = (_c) => __awaiter(void 0, [_c], void 0, function* ({ environmentId, primaryWalletId, walletId, onSuccess, }) {
    // 7702 wallets have a -zerodev suffix because it's a credential created on the fly
    const normalizedPrimaryWalletId = primaryWalletId === null || primaryWalletId === void 0 ? void 0 : primaryWalletId.replace('-zerodev', '');
    try {
        const response = yield sdkApi().verifyUnlink({
            environmentId,
            verifyUnlinkRequest: {
                primaryWalletId: normalizedPrimaryWalletId,
                walletId,
            },
        });
        onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess();
        const user = storeTokenAndUser(response);
        return user;
    }
    catch (e) {
        const data = yield logResponseError(e, 'Error transfering wallet');
        throw new DynamicError(data.error);
    }
});
const transferWallet = (environmentId_2, _d) => __awaiter(void 0, [environmentId_2, _d], void 0, function* (environmentId, { network, messageToSign, signedMessage, publicWalletAddress, chain, walletName, walletProvider, skipEmptyAccountCheck = false, }) {
    // We should find a better way to do this than force type casting
    const verifyRequest = {
        chain,
        messageToSign,
        network,
        publicWalletAddress,
        signedMessage,
        skipEmptyAccountCheck,
        walletName,
        walletProvider,
    };
    try {
        const response = yield sdkApi().verifyTransfer({
            environmentId,
            verifyRequest,
        });
        const user = storeTokenAndUser(response);
        return user;
    }
    catch (e) {
        const data = yield logResponseError(e, 'Error transfering wallet');
        throw new DynamicError(data.error);
    }
});
const verifyWallet = (environmentId_3, _e) => __awaiter(void 0, [environmentId_3, _e], void 0, function* (environmentId, { messageToSign, signedMessage, publicWalletAddress, chain, walletName, walletProvider, captchaToken, network, oauth, additionalWalletAddresses, sessionPublicKey, }) {
    const verifyRequest = VerifyRequestFromJSON({
        additionalWalletAddresses,
        captchaToken,
        chain,
        messageToSign,
        network,
        oauth,
        publicWalletAddress,
        sessionPublicKey,
        signedMessage,
        walletName,
        walletProvider,
    });
    try {
        const response = yield sdkApi().verify({
            environmentId,
            verifyRequest,
        });
        return response;
    }
    catch (e) {
        const data = yield logResponseError(e, 'Error verifyWallet');
        if (data.code === 'wallet_not_deployed') {
            throw new WalletNotDeployedError();
        }
        if (data.error.code === 'chainalysis_blocked_wallet') {
            throw new ChainalysisError(data.payload.walletPublicKey);
        }
        if (data.error.code === 'gate_blocked') {
            throw new GateBlockedError(data.payload.walletPublicKey);
        }
        if (data.error.code === 'missing_from_list') {
            throw new NoAccessError({
                walletPublicKey: data.payload.walletPublicKey,
            });
        }
        if (data.code === 'email_associated_with_different_provider') {
            throw new AccountExistsError(data.error, data.payload);
        }
        if (data.error.code === 'sandbox_maximum_threshold_reached') {
            throw new SandboxMaximumThresholdReachedError(data.error.message);
        }
        throw new DynamicError(data.error);
    }
});
const upgradeEmbeddedWalletToV2 = (_f) => __awaiter(void 0, [_f], void 0, function* ({ environmentId, sessionPublicKey, }) {
    try {
        const response = yield sdkApi().upgradeEmbeddedWalletToV2({
            environmentId,
            upgradeEmbeddedWalletToV2Request: { sessionPublicKey },
        });
        return response;
    }
    catch (e) {
        const data = yield logResponseError(e, 'Error upgradeEmbeddedWalletToV2');
        throw new DynamicError(data.error);
    }
});
const softDeleteEmbeddedWallet = (_g) => __awaiter(void 0, [_g], void 0, function* ({ environmentId, walletId, }) {
    try {
        yield sdkApi().softDeleteEmbeddedWallet({
            environmentId,
            walletId,
        });
    }
    catch (e) {
        const data = yield logResponseError(e, `Error softDeleteEmbeddedWallet for ${walletId} in ${environmentId}`);
        throw new DynamicError(data.error);
    }
});
const restoreEmbeddedWallet = (_h) => __awaiter(void 0, [_h], void 0, function* ({ environmentId, walletId, }) {
    try {
        yield sdkApi().restoreEmbeddedWallet({
            environmentId,
            walletId,
        });
    }
    catch (e) {
        const data = yield logResponseError(e, `Error restoreEmbeddedWallet for ${walletId} in ${environmentId}`);
        throw new DynamicError(data.error);
    }
});

export { linkWallet, restoreEmbeddedWallet, softDeleteEmbeddedWallet, storeSelectedWallet, transferWallet, unlinkWallet, upgradeEmbeddedWalletToV2, verifyWallet };
