'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var client = require('@dynamic-labs-sdk/client');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var verifyTotpMfaDevice = require('../../../client/extension/deprecated/mfa/verifyTotpMfaDevice/verifyTotpMfaDevice.cjs');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
require('../../../context/ViewContext/ViewContext.cjs');
require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs/locale');
var user = require('../../../data/api/user/user.cjs');
var dynamicContextProps = require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
var useUserAuth = require('../useUserAuth/useUserAuth.cjs');

const useMfa = () => {
    const { completeAuth } = useUserAuth.useUserAuth({});
    const handleMfaAuth = React.useCallback((_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ code, type, deviceId, createMfaToken, resultHandler, }) {
        let result;
        yield completeAuth({
            updateJwtFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                if (type !== sdkApiCore.MFADeviceType.Totp) {
                    throw new Error('Only Totp is supported');
                }
                const response = yield client.authenticateTotpMfaDevice({
                    code,
                    createMfaTokenOptions: createMfaToken,
                    deviceId,
                });
                result = resultHandler(response);
                return {
                    isEmailVerificationRequired: false,
                    isSmsVerificationRequired: false,
                    missingFields: [],
                    updateUserProfileResponse: response,
                };
            }),
        });
        return result;
    }), [completeAuth]);
    const getUserDevices = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const devices = yield client.getMfaDevices();
        return devices;
    }), []);
    const updateUserDevice = React.useCallback((deviceId) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const devices = yield client.getMfaDevices();
        const device = devices.find((d) => d.id === deviceId);
        if (!device) {
            throw new Error('Device not found');
        }
        yield client.setDefaultMfaDevice({ deviceId });
    }), []);
    const deleteUserDevice = React.useCallback((deviceId, mfaAuthToken) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const devices = yield client.getMfaDevices();
        const device = devices.find((d) => d.id === deviceId);
        if (!device) {
            throw new Error('Device not found');
        }
        yield client.deleteMfaDevice({
            deviceId,
            mfaAuthToken,
        });
        // Refresh the user JWT to get the updated MFA acknowledgement
        // since if it is completed we won't show the QR code again
        yield user.refreshUserJwt({ environmentId: dynamicContextProps.getEnvironmentId() });
    }), []);
    const addDevice = React.useCallback((...args_1) => _tslib.__awaiter(void 0, [...args_1], void 0, function* (type = sdkApiCore.MFADeviceType.Totp) {
        if (type === sdkApiCore.MFADeviceType.Totp) {
            return client.registerTotpMfaDevice();
        }
        throw new Error('Unsupported MFA device type');
    }), []);
    const authDevice = React.useCallback((code_1, ...args_2) => _tslib.__awaiter(void 0, [code_1, ...args_2], void 0, function* (code, type = sdkApiCore.MFADeviceType.Totp, deviceId) {
        let isValid = false;
        yield handleMfaAuth({
            code,
            deviceId,
            resultHandler: () => {
                isValid = true;
                return true;
            },
            type,
        });
        return isValid;
    }), [handleMfaAuth]);
    const authenticateDevice = React.useCallback((_b) => _tslib.__awaiter(void 0, [_b], void 0, function* ({ code, type = sdkApiCore.MFADeviceType.Totp, deviceId, createMfaToken, }) {
        return handleMfaAuth({
            code,
            createMfaToken,
            deviceId,
            resultHandler: (response) => response.mfaToken,
            type,
        });
    }), [handleMfaAuth]);
    const authRecoveryCode = React.useCallback((code) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        let isValid = false;
        yield completeAuth({
            onValidUpdatedJwt: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                isValid = true;
            }),
            updateJwtFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                const response = yield client.authenticateMfaRecoveryCode({
                    code,
                    createMfaTokenOptions: { singleUse: true },
                });
                if (!response) {
                    throw new Error('Failed to authenticate recovery code');
                }
                dynamicEvents.dynamicEvents.emit('mfaCompletionSuccess', {
                    mfaToken: response.mfaToken,
                });
                return {
                    isEmailVerificationRequired: false,
                    isSmsVerificationRequired: false,
                    missingFields: [],
                    // in the mfa flow, we only care about the user in the response
                    updateUserProfileResponse: response,
                };
            }),
        });
        return isValid;
    }), [completeAuth]);
    const authenticateRecoveryCode = React.useCallback((_c) => _tslib.__awaiter(void 0, [_c], void 0, function* ({ code, createMfaToken, }) {
        let mfaToken = undefined;
        yield completeAuth({
            updateJwtFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                const response = yield client.authenticateMfaRecoveryCode({
                    code,
                    createMfaTokenOptions: createMfaToken,
                });
                if (!response) {
                    throw new Error('Failed to authenticate recovery code');
                }
                // eslint-disable-next-line prefer-destructuring
                mfaToken = response.mfaToken;
                dynamicEvents.dynamicEvents.emit('mfaCompletionSuccess', {
                    mfaToken: response.mfaToken,
                });
                return {
                    isEmailVerificationRequired: false,
                    isSmsVerificationRequired: false,
                    missingFields: [],
                    // in the mfa flow, we only care about the user in the response
                    updateUserProfileResponse: response,
                };
            }),
        });
        return mfaToken;
    }), [completeAuth]);
    const verifyDevice = React.useCallback((code_2, ...args_3) => _tslib.__awaiter(void 0, [code_2, ...args_3], void 0, function* (code, type = sdkApiCore.MFADeviceType.Totp) {
        if (type === sdkApiCore.MFADeviceType.Totp) {
            const device = yield verifyTotpMfaDevice.verifyTotpMfaDevice({
                code,
            });
            if (!device) {
                throw new Error('Failed to verify device');
            }
            return device;
        }
        throw new Error('Unsupported MFA device type');
    }), []);
    const getRecoveryCodes = React.useCallback((...args_4) => _tslib.__awaiter(void 0, [...args_4], void 0, function* (
    /**
     * @deprecated use getNewRecoveryCodes instead
     */
    generateNewCodes = false) {
        if (generateNewCodes) {
            const { recoveryCodes } = yield client.createNewMfaRecoveryCodes();
            return recoveryCodes;
        }
        else {
            const { recoveryCodes } = yield client.getMfaRecoveryCodes();
            return recoveryCodes;
        }
    }), []);
    const getNewRecoveryCodes = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const { recoveryCodes } = yield client.createNewMfaRecoveryCodes();
        return recoveryCodes;
    }), []);
    const isPendingRecoveryCodesAcknowledgment = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () { return client.isPendingRecoveryCodesAcknowledgment(); }), []);
    const completeAcknowledgement = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        yield client.acknowledgeRecoveryCodes();
    }), []);
    return {
        addDevice,
        authDevice,
        authRecoveryCode,
        authenticateDevice,
        authenticateRecoveryCode,
        completeAcknowledgement,
        deleteUserDevice,
        getNewRecoveryCodes,
        getRecoveryCodes,
        getUserDevices,
        isPendingRecoveryCodesAcknowledgment,
        updateUserDevice,
        verifyDevice,
    };
};

exports.useMfa = useMfa;
