import { create } from 'zustand';
const createKey = (key) => key.join('-');
export const useOperationStore = create()(set => ({
    statusById: {},
    onPending: (id) => {
        set(state => ({
            statusById: {
                ...state.statusById,
                [createKey(id)]: { status: 'pending', data: undefined, error: null },
            },
        }));
    },
    onSuccess: (id, data) => {
        set(state => ({
            statusById: {
                ...state.statusById,
                [createKey(id)]: { status: 'success', data, error: null },
            },
        }));
    },
    onError: (id, error) => {
        set(state => ({
            statusById: {
                ...state.statusById,
                [createKey(id)]: { status: 'error', data: undefined, error },
            },
        }));
    },
    onIdle: (id) => {
        set(state => ({
            statusById: {
                ...state.statusById,
                [createKey(id)]: { status: 'idle', data: undefined, error: null },
            },
        }));
    },
}));
export const runOperation = async (operation) => {
    useOperationStore.getState().onPending(operation.key);
    try {
        const data = await operation.fn();
        useOperationStore.getState().onSuccess(operation.key, data);
        return data;
    }
    catch (error) {
        useOperationStore.getState().onError(operation.key, error);
        throw error;
    }
};
export const runOperationsMany = async (operations) => {
    const results = await Promise.all(operations.map(operation => runOperation(operation)));
    return results;
};
const idleState = { status: 'idle', data: undefined, error: null };
export const useOperation = (operation) => {
    const status = useOperationStore(state => state.statusById[createKey(operation.key)]);
    return status ?? idleState;
};
export const useOperationWithKey = (key) => {
    const status = useOperationStore(state => state.statusById[createKey(key)]);
    return status ?? idleState;
};
export const useManyOperations = (operations) => {
    const statuses = useOperationStore(state => operations.map(operation => state.statusById[createKey(operation.key)]));
    return statuses.map(status => status ?? idleState);
};
