'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { getElevatedAccessToken } from '@dynamic-labs-sdk/client';
import { TokenScope, VerifyRequestFromJSON } from '@dynamic-labs/sdk-api-core';
import { DynamicError, EmbeddedWalletExistsError, WalletUsedError, MergeAccountsConfirmationError, SandboxMaximumThresholdReachedError, SdkErrorCode, WalletNotDeployedError, ChainalysisError, GateBlockedError, NoAccessError, ErrorCode, AccountExistsError } from '@dynamic-labs/utils';
import '@dynamic-labs-sdk/client/core';
import 'react';
import 'eventemitter3';
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 '@dynamic-labs-wallet/browser-wallet-client';
import { sdkApi } from '../api.js';
import { ELEVATED_ACCESS_TOKEN_HEADER } from '../constants.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 '../../../utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.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, data.code);
    }
});
const linkWallet = (environmentId_1, _b) => __awaiter(void 0, [environmentId_1, _b], void 0, function* (environmentId, { messageToSign, network, signedMessage, publicWalletAddress, chain, walletName, walletProvider, additionalWalletAddresses, backup, }) {
    var _c;
    const verifyRequest = VerifyRequestFromJSON({
        additionalWalletAddresses,
        backup,
        chain,
        messageToSign,
        network,
        publicWalletAddress,
        signedMessage,
        walletName,
        walletProvider,
    });
    try {
        const elevatedToken = getElevatedAccessToken({
            scope: TokenScope.Credentiallink,
        });
        const response = yield sdkApi({
            customHeaders: elevatedToken
                ? { [ELEVATED_ACCESS_TOKEN_HEADER]: elevatedToken }
                : undefined,
        }).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 (((_c = data.error) === null || _c === void 0 ? void 0 : _c.code) === 'sandbox_maximum_threshold_reached') {
            throw new SandboxMaximumThresholdReachedError(data.error.message);
        }
        throw new DynamicError(data.error, data.code);
    }
});
const unlinkWallet = (_d) => __awaiter(void 0, [_d], 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 elevatedToken = getElevatedAccessToken({
            scope: TokenScope.Credentialunlink,
        });
        const response = yield sdkApi({
            customHeaders: elevatedToken
                ? { [ELEVATED_ACCESS_TOKEN_HEADER]: elevatedToken }
                : undefined,
        }).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, data.code);
    }
});
const transferWallet = (environmentId_2, _e) => __awaiter(void 0, [environmentId_2, _e], 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, data.code);
    }
});
const verifyWallet = (environmentId_3, _f) => __awaiter(void 0, [environmentId_3, _f], void 0, function* (environmentId, { messageToSign, signedMessage, publicWalletAddress, chain, walletName, walletProvider, captchaToken, network, oauth, additionalWalletAddresses, sessionPublicKey, }) {
    var _g, _h, _j, _k;
    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 === SdkErrorCode.WALLET_NOT_DEPLOYED) {
            throw new WalletNotDeployedError();
        }
        if (((_g = data.error) === null || _g === void 0 ? void 0 : _g.code) === 'chainalysis_blocked_wallet') {
            throw new ChainalysisError(data.payload.walletPublicKey, data.error.code);
        }
        if (((_h = data.error) === null || _h === void 0 ? void 0 : _h.code) === 'gate_blocked') {
            throw new GateBlockedError(data.payload.walletPublicKey);
        }
        if (((_j = data.error) === null || _j === void 0 ? void 0 : _j.code) === 'missing_from_list') {
            throw new NoAccessError({
                code: data.error.code,
                walletPublicKey: data.payload.walletPublicKey,
            });
        }
        if (data.code === 'credential_not_enabled_for_sign_in') {
            throw new DynamicError(data.error, ErrorCode.CREDENTIAL_NOT_ENABLED_FOR_SIGN_IN);
        }
        if (data.code === 'email_associated_with_different_provider') {
            throw new AccountExistsError(data.error, data.payload, data.code);
        }
        if (((_k = data.error) === null || _k === void 0 ? void 0 : _k.code) === 'sandbox_maximum_threshold_reached') {
            throw new SandboxMaximumThresholdReachedError(data.error.message);
        }
        throw new DynamicError(data.error, data.code);
    }
});
const walletsVerify = (environmentId_4, _l) => __awaiter(void 0, [environmentId_4, _l], void 0, function* (environmentId, { messageToSign, signedMessage, publicWalletAddress, chain, walletName, walletProvider, captchaToken, network, oauth, requestedScopes, additionalWalletAddresses, sessionPublicKey, }) {
    var _m, _o, _p, _q;
    const verifyRequest = VerifyRequestFromJSON({
        additionalWalletAddresses,
        captchaToken,
        chain,
        messageToSign,
        network,
        oauth,
        publicWalletAddress,
        requestedScopes,
        sessionPublicKey,
        signedMessage,
        walletName,
        walletProvider,
    });
    try {
        const response = yield sdkApi().walletsVerify({
            environmentId,
            verifyRequest,
        });
        return response;
    }
    catch (e) {
        const data = yield logResponseError(e, 'Error walletsVerify');
        if (data.code === SdkErrorCode.WALLET_NOT_DEPLOYED) {
            throw new WalletNotDeployedError();
        }
        if (((_m = data.error) === null || _m === void 0 ? void 0 : _m.code) === 'chainalysis_blocked_wallet') {
            throw new ChainalysisError(data.payload.walletPublicKey, data.error.code);
        }
        if (((_o = data.error) === null || _o === void 0 ? void 0 : _o.code) === 'gate_blocked') {
            throw new GateBlockedError(data.payload.walletPublicKey);
        }
        if (((_p = data.error) === null || _p === void 0 ? void 0 : _p.code) === 'missing_from_list') {
            throw new NoAccessError({
                code: data.error.code,
                walletPublicKey: data.payload.walletPublicKey,
            });
        }
        if (data.code === 'credential_not_enabled_for_sign_in') {
            throw new DynamicError(data.error, ErrorCode.CREDENTIAL_NOT_ENABLED_FOR_SIGN_IN);
        }
        if (data.code === 'email_associated_with_different_provider') {
            throw new AccountExistsError(data.error, data.payload, data.code);
        }
        if (((_q = data.error) === null || _q === void 0 ? void 0 : _q.code) === 'sandbox_maximum_threshold_reached') {
            throw new SandboxMaximumThresholdReachedError(data.error.message);
        }
        throw new DynamicError(data.error, data.code);
    }
});
const upgradeEmbeddedWalletToV2 = (_r) => __awaiter(void 0, [_r], 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, data.code);
    }
});
const softDeleteEmbeddedWallet = (_s) => __awaiter(void 0, [_s], 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, data.code);
    }
});
const restoreEmbeddedWallet = (_t) => __awaiter(void 0, [_t], 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, data.code);
    }
});

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