import { jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
import { sanitizeStoredModel } from '../lib/credentialUtils';
const noopAsync = async () => { };
const defaultStatus = { status: 'idle', updatedAt: 0 };
const CredentialContext = React.createContext({
    submitCredentials: noopAsync,
    getStatus: () => defaultStatus,
    resetStatus: () => { },
    isLoadingInitialCredentials: false,
    credentialError: undefined
});
export const CredentialSyncProvider = ({ children, onSubmit, onRefresh, initialLoading = false, initialError }) => {
    const [statusMap, setStatusMap] = React.useState({});
    const [isLoadingInitialCredentials, setIsLoadingInitialCredentials] = React.useState(initialLoading);
    const [credentialError, setCredentialError] = React.useState(initialError);
    React.useEffect(() => {
        setIsLoadingInitialCredentials(initialLoading);
    }, [initialLoading]);
    React.useEffect(() => {
        setCredentialError(initialError);
    }, [initialError]);
    const getStatus = React.useCallback((providerId) => {
        return statusMap[providerId] ?? defaultStatus;
    }, [statusMap]);
    const resetStatus = React.useCallback((providerId) => {
        setStatusMap((prev) => {
            if (!prev[providerId])
                return prev;
            const next = { ...prev };
            delete next[providerId];
            return next;
        });
    }, []);
    const submitCredentials = React.useCallback(async (payload) => {
        const { providerId } = payload;
        const existingStatus = getStatus(providerId);
        if (existingStatus.status === 'pending') {
            return;
        }
        const sanitizedModel = payload.model ? sanitizeStoredModel(payload.model) : null;
        const sanitizedAllModels = payload.allModels.map((model) => sanitizeStoredModel(model));
        setStatusMap((prev) => ({
            ...prev,
            [providerId]: { status: 'pending', updatedAt: Date.now() }
        }));
        try {
            if (onSubmit) {
                await onSubmit({
                    ...payload,
                    model: sanitizedModel,
                    allModels: sanitizedAllModels
                });
            }
            setStatusMap((prev) => ({
                ...prev,
                [providerId]: { status: 'success', updatedAt: Date.now() }
            }));
            if (onRefresh) {
                await onRefresh();
            }
        }
        catch (error) {
            setStatusMap((prev) => ({
                ...prev,
                [providerId]: { status: 'error', error, updatedAt: Date.now() }
            }));
            throw error;
        }
    }, [getStatus, onSubmit, onRefresh]);
    const value = React.useMemo(() => ({
        submitCredentials,
        getStatus,
        resetStatus,
        isLoadingInitialCredentials,
        credentialError
    }), [
        submitCredentials,
        getStatus,
        resetStatus,
        isLoadingInitialCredentials,
        credentialError
    ]);
    return (_jsx(CredentialContext.Provider, { value: value, children: children }));
};
export const useCredentialSync = (providerId) => {
    const context = React.useContext(CredentialContext);
    if (!context) {
        throw new Error('useCredentialSync must be used within a CredentialSyncProvider');
    }
    const status = providerId ? context.getStatus(providerId) : defaultStatus;
    return {
        submitCredentials: context.submitCredentials,
        resetStatus: context.resetStatus,
        status,
        isLoadingInitialCredentials: context.isLoadingInitialCredentials,
        credentialError: context.credentialError
    };
};
export default CredentialContext;
