import { useCallback } from 'react';
import { useProjectStore } from '@lib/store/project';
import { loadCanvasStateFromStorage } from '../services/storage';
import { useCanvasStore } from '@lib/store/canvasStore';
import { getHistoryKey } from './persistenceUtils';

export const useGenerationHistory = () => {
    const projectId = useProjectStore((s) => s.id);
    const setGenerationHistory = useCanvasStore(state => state.setGenerationHistory);
    const addGenerationHistoryItem = useCanvasStore(state => state.addGenerationHistoryItem);

    // Load Global History
    // This effect runs once on mount or when projectId changes
    // It loads the history that is shared/global
    const loadHistory = useCallback(async () => {
        const key = getHistoryKey(projectId);
        try {
            const savedData = await loadCanvasStateFromStorage<{ history: any[] }>(key, projectId || undefined);
            if (savedData && savedData.history) {
                setGenerationHistory(savedData.history);
            }
        } catch (e) {
            console.error("Failed to load history", e);
        }
    }, [projectId, setGenerationHistory]);

    return {
        loadHistory,
        addHistoryItem: addGenerationHistoryItem
    };
};
