import { ref } from "vue";
import { defineStore } from "pinia";
import { apiGet, apiPost, apiPut, apiPatch, apiDelete } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import type { Task, TaskStatus, TaskPriority, StartPlanningResult } from "@/types/task";
import type { TaskKind } from "@/types/note";

// Issues + Systems write-only fields accepted by the task create/update API.
// `kind` selects work/plan/issue; system_ids / arose_from_id are not mirrored
// 1:1 on the Task model (the read side exposes `systems` + `arose_from_id`).
interface IssueFields {
  kind?: TaskKind;
  system_ids?: number[];
  arose_from_id?: number | null;
}

// Single-task + mutation surface. The list/filter/sort/pagination surface that
// backed the removed /tasks list view was dropped in the 2026-06-02 drift-audit
// cleanup (no consumers — ProjectView's kanban keeps its own local task list).
export const useTasksStore = defineStore("tasks", () => {
  const currentTask = ref<Task | null>(null);
  const loading = ref(false);

  async function fetchTask(id: number) {
    loading.value = true;
    try {
      currentTask.value = await apiGet<Task>(`/api/tasks/${id}`);
    } catch (e) {
      useToastStore().show("Failed to load task", "error");
      throw e;
    } finally {
      loading.value = false;
    }
  }

  async function createTask(data: {
    title: string;
    body: string;
    tags?: string[];
    status?: TaskStatus;
    priority?: TaskPriority;
    due_date?: string | null;
    project_id?: number | null;
    milestone_id?: number | null;
    parent_id?: number | null;
    recurrence_rule?: Record<string, unknown> | null;
  } & IssueFields): Promise<Task> {
    try {
      return await apiPost<Task>("/api/tasks", data);
    } catch (e) {
      useToastStore().show("Failed to create task", "error");
      throw e;
    }
  }

  async function updateTask(
    id: number,
    data: Partial<
      Pick<Task, "title" | "body" | "tags" | "status" | "priority" | "due_date" | "project_id" | "milestone_id" | "parent_id" | "recurrence_rule">
    > & IssueFields
  ): Promise<Task> {
    try {
      const task = await apiPut<Task>(`/api/tasks/${id}`, data);
      if (currentTask.value?.id === id) {
        currentTask.value = task;
      }
      return task;
    } catch (e) {
      useToastStore().show("Failed to update task", "error");
      throw e;
    }
  }

  async function patchStatus(id: number, status: TaskStatus): Promise<Task> {
    try {
      const task = await apiPatch<Task>(`/api/tasks/${id}/status`, { status });
      if (currentTask.value?.id === id) {
        currentTask.value = task;
      }
      return task;
    } catch (e) {
      useToastStore().show("Failed to update task status", "error");
      throw e;
    }
  }

  async function deleteTask(id: number) {
    try {
      await apiDelete(`/api/tasks/${id}`);
      if (currentTask.value?.id === id) {
        currentTask.value = null;
      }
    } catch (e) {
      useToastStore().show("Failed to delete task", "error");
      throw e;
    }
  }

  async function startPlanning(
    projectId: number,
    title: string
  ): Promise<StartPlanningResult> {
    try {
      return await apiPost<StartPlanningResult>("/api/tasks/planning", {
        project_id: projectId,
        title,
      });
    } catch (e) {
      useToastStore().show("Failed to start planning", "error");
      throw e;
    }
  }

  return {
    currentTask,
    loading,
    fetchTask,
    createTask,
    updateTask,
    patchStatus,
    deleteTask,
    startPlanning,
  };
});
