import { defineStore } from "pinia";

export interface ImportTask {
  id: string;
  fileName: string;
  status: "pending" | "uploading" | "processing" | "success" | "error";
  message: string;
  totalRows: number;
  processedRows: number;
  createdAt: number;
  completedAt: number | null;
  backendTaskId: string;
}

export const useImportTaskStore = defineStore("useImportTaskStore", {
  state: () => ({
    tasks: [] as ImportTask[]
  }),
  getters: {
    activeTasks(state): ImportTask[] {
      return state.tasks.filter((t) => t.status === "pending" || t.status === "uploading" || t.status === "processing");
    },
    hasActiveTasks(state): boolean {
      return state.tasks.some((t) => t.status === "pending" || t.status === "uploading" || t.status === "processing");
    },
    recentTasks(state): ImportTask[] {
      return [...state.tasks].sort((a, b) => b.createdAt - a.createdAt);
    }
  },
  actions: {
    addTask(task: ImportTask) {
      this.tasks.push(task);
    },
    updateTask(id: string, data: Partial<ImportTask>) {
      const idx = this.tasks.findIndex((t) => t.id === id);
      if (idx !== -1) {
        this.tasks[idx] = { ...this.tasks[idx], ...data };
      }
    },
    removeTask(id: string) {
      this.tasks = this.tasks.filter((t) => t.id !== id);
    },
    clearCompleted() {
      this.tasks = this.tasks.filter((t) => t.status === "pending" || t.status === "uploading" || t.status === "processing");
    }
  }
});
