'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { SocialAccountAlreadyExistsError, SandboxMaximumThresholdReachedError, GateBlockedError, NoAccessError, AccountExistsError } from '@dynamic-labs/utils';
import '@dynamic-labs-sdk/client/core';
import '@dynamic-labs/sdk-api-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 { 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 '@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 initAuth = (environmentId, providerType, oauthInitAuthRequest) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        yield sdkApi().initAuth({
            environmentId,
            oauthInitAuthRequest,
            providerType,
        });
    }
    catch (err) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        let data;
        try {
            data = yield err.json();
            logger.error(data);
        }
        catch (_a) {
            logger.error(err);
            throw err;
        }
        throw new Error(data.error);
    }
});
const verifyOAuth = (environmentId_1, providerType_1, _b) => __awaiter(void 0, [environmentId_1, providerType_1, _b], void 0, function* (environmentId, providerType, { code, codeVerifier, state }) {
    const oauthRequest = {
        code,
        codeVerifier,
        state,
    };
    try {
        const response = yield sdkApi().oauthVerify({
            environmentId,
            oauthRequest,
            providerType,
        });
        return storeTokenAndUser(response);
    }
    catch (e) {
        return handleVerifyError(e);
    }
});
const unlinkOAuth = (_c) => __awaiter(void 0, [_c], void 0, function* ({ environmentId, primaryWalletId, verifiedCredentialId, }) {
    // 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,
                verifiedCredentialId,
            },
        });
        const user = storeTokenAndUser(response);
        return user;
    }
    catch (e) {
        return undefined;
    }
});
const signInOAuth = (environmentId_2, providerType_2, _d) => __awaiter(void 0, [environmentId_2, providerType_2, _d], void 0, function* (environmentId, providerType, { code, codeVerifier, state, captchaToken, sessionPublicKey, ssoProviderId, }) {
    const oauthRequest = {
        captchaToken,
        code,
        codeVerifier,
        sessionPublicKey,
        ssoProviderId,
        state,
    };
    try {
        const response = yield sdkApi().oauthSignIn({
            environmentId,
            oauthRequest,
            providerType,
        });
        const user = storeTokenAndUser(response);
        return user;
    }
    catch (e) {
        return handleSignInError(e);
    }
});
const getOAuthResult = (environmentId_3, providerType_3, _e) => __awaiter(void 0, [environmentId_3, providerType_3, _e], void 0, function* (environmentId, providerType, { state }) {
    const oauthResultRequest = {
        state,
    };
    try {
        const result = yield sdkApi().oauthResult({
            environmentId,
            oauthResultRequest,
            providerType,
        });
        return result;
    }
    catch (e) {
        yield logResponseError(e, 'error getting oauth result');
        return undefined;
    }
});
const farcasterSignIn = (environmentId, farcasterSignInRequest) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const response = yield sdkApi().farcasterSignIn({
            environmentId,
            farcasterSignInRequest,
        });
        const user = storeTokenAndUser(response);
        return user;
    }
    catch (e) {
        return handleSignInError(e);
    }
});
const farcasterVerify = (farcasterVerifyRequest) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const response = yield sdkApi().farcasterVerify(farcasterVerifyRequest);
        const user = storeTokenAndUser(response);
        return user;
    }
    catch (e) {
        return handleVerifyError(e);
    }
});
const telegramSignIn = (environmentId, oauthResultRequest) => __awaiter(void 0, void 0, void 0, function* () {
    const telegramSignInRequest = {
        environmentId,
        oauthResultRequest,
    };
    try {
        const response = yield sdkApi().telegramSignIn(telegramSignInRequest);
        const user = storeTokenAndUser(response);
        return user;
    }
    catch (e) {
        return handleSignInError(e);
    }
});
const isUserLinkedWithTelegram = (environmentId, oauthResultRequest) => __awaiter(void 0, void 0, void 0, function* () {
    const telegramCheckAuthRequest = {
        environmentId,
        oauthResultRequest,
    };
    try {
        yield sdkApi().telegramCheckAuth(telegramCheckAuthRequest);
        return true;
    }
    catch (e) {
        return false;
    }
});
const telegramVerify = (environmentId, oauthResultRequest) => __awaiter(void 0, void 0, void 0, function* () {
    const telegramVerifyRequest = {
        environmentId,
        oauthResultRequest,
    };
    try {
        const response = yield sdkApi().telegramVerify(telegramVerifyRequest);
        const user = storeTokenAndUser(response);
        return user;
    }
    catch (e) {
        return handleVerifyError(e);
    }
});
const handleVerifyError = (e) => __awaiter(void 0, void 0, void 0, function* () {
    const data = yield logResponseError(e, 'error verifying social');
    if (data.code === 'social_account_already_exists') {
        throw new SocialAccountAlreadyExistsError();
    }
    if (data.error.code === 'sandbox_maximum_threshold_reached') {
        throw new SandboxMaximumThresholdReachedError(data.error.message);
    }
    return undefined;
});
const handleSignInError = (e) => __awaiter(void 0, void 0, void 0, function* () {
    var _f, _g, _h;
    const data = yield logResponseError(e, 'error signin social');
    if (data.error.code === 'gate_blocked') {
        throw new GateBlockedError(data.payload.walletPublicKey);
    }
    if (data.error.code === 'missing_from_list') {
        throw new NoAccessError({
            socialProvider: (_f = data === null || data === void 0 ? void 0 : data.payload) === null || _f === void 0 ? void 0 : _f.socialProvider,
            socialUsername: (_g = data === null || data === void 0 ? void 0 : data.payload) === null || _g === void 0 ? void 0 : _g.socialUsername,
            walletPublicKey: (_h = data === null || data === void 0 ? void 0 : data.payload) === null || _h === void 0 ? void 0 : _h.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);
    }
    return undefined;
});

export { farcasterSignIn, farcasterVerify, getOAuthResult, initAuth, isUserLinkedWithTelegram, signInOAuth, telegramSignIn, telegramVerify, unlinkOAuth, verifyOAuth };
