import { ref } from "vue";
import { defineStore } from "pinia";
import * as api from "@/api/systems";
import type { System } from "@/api/systems";
import { useToastStore } from "@/stores/toast";

export const useSystemsStore = defineStore("systems", () => {
  const systemsByProject = ref<Record<number, System[]>>({});
  const loading = ref(false);

  async function fetchSystems(projectId: number) {
    loading.value = true;
    try {
      systemsByProject.value[projectId] = await api.listSystems(projectId);
    } catch (e) {
      useToastStore().show("Failed to load systems", "error");
      throw e;
    } finally {
      loading.value = false;
    }
  }

  async function createSystem(
    projectId: number,
    data: { name: string; description?: string; color?: string },
  ) {
    const system = await api.createSystem(projectId, data);
    if (!systemsByProject.value[projectId]) systemsByProject.value[projectId] = [];
    systemsByProject.value[projectId].push(system);
    return system;
  }

  async function updateSystem(
    projectId: number,
    systemId: number,
    data: Partial<Pick<System, "name" | "description" | "color" | "status" | "order_index">>,
  ) {
    const system = await api.updateSystem(projectId, systemId, data);
    const list = systemsByProject.value[projectId];
    if (list) {
      const idx = list.findIndex((s) => s.id === systemId);
      if (idx >= 0) list[idx] = system;
    }
    return system;
  }

  async function archiveSystem(projectId: number, systemId: number) {
    return updateSystem(projectId, systemId, { status: "archived" });
  }

  async function unarchiveSystem(projectId: number, systemId: number) {
    return updateSystem(projectId, systemId, { status: "active" });
  }

  async function deleteSystem(projectId: number, systemId: number) {
    await api.deleteSystem(projectId, systemId);
    const list = systemsByProject.value[projectId];
    if (list) {
      systemsByProject.value[projectId] = list.filter((s) => s.id !== systemId);
    }
  }

  return {
    systemsByProject,
    loading,
    fetchSystems,
    createSystem,
    updateSystem,
    archiveSystem,
    unarchiveSystem,
    deleteSystem,
  };
});
