import { create } from 'zustand';
import type { WebGenerationPreviewTask } from '../types';

interface TaskState {
  tasks: WebGenerationPreviewTask[];
}

interface TaskActions {
  setTasks: (tasks: WebGenerationPreviewTask[]) => void;
  appendTask: (task: WebGenerationPreviewTask) => void;
  mergeServerTasks: (serverTasks: WebGenerationPreviewTask[]) => void;
  clearTasks: () => void;
}

const initialState: TaskState = {
  tasks: [],
};

export const useTaskStore = create<TaskState & TaskActions>((set) => ({
  ...initialState,

  setTasks: (tasks) => set({ tasks }),

  appendTask: (task) => set((state) => ({
    tasks: [task, ...state.tasks],
  })),

  mergeServerTasks: (serverTasks) => set((state) => {
    const serverIds = new Set(serverTasks.map((task) => task.id));
    return {
      tasks: [...serverTasks, ...state.tasks.filter((task) => !serverIds.has(task.id))].slice(0, 80),
    };
  }),

  clearTasks: () => set({ tasks: [] }),
}));
