import { fetchJson } from "@/api/client";
import type { ApiResult } from "@/types";

export type TaskTreeGroup = { id: string; name: string; description: string; createdAt: string; updatedAt: string };
export type TaskTreeTask = { id: string; groupId: string; parentId: string | null; kind: "task" | "subtask" | "subsubtask"; outlineRef: string; title: string; description: string; status: string; startAt: string | null; dueAt: string | null; sortOrder: number; createdAt: string; updatedAt: string };
export type TaskTreeMilestone = { id: string; groupId: string; taskId: string | null; title: string; occursAt: string; createdAt: string };
export type TaskTreeReport = { id: string; taskId: string; title: string; body: string; status: string; createdAt: string };
export type TaskTreeTimeline = { group: TaskTreeGroup; tasks: TaskTreeTask[]; milestones: TaskTreeMilestone[]; reports: TaskTreeReport[] };
export type TaskTreeGroupOverview = { group: TaskTreeGroup; taskCount: number; subtaskCount: number; subsubtaskCount: number; reportCount: number; startAt: string | null; dueAt: string | null };
type Result<T> = { ok?: boolean; data?: T; error?: { code?: string; message?: string } };

export const tasktreeAPI = {
  groups: (): Promise<ApiResult<Result<{ groups: TaskTreeGroup[] }>>> => fetchJson("/v1/tasktree/groups", { timeoutMs: 12000, timeoutName: "TaskTree groups" }),
  overview: (): Promise<ApiResult<Result<{ groups: TaskTreeGroupOverview[] }>>> => fetchJson("/v1/tasktree/overview", { timeoutMs: 12000, timeoutName: "TaskTree overview" }),
  timeline: (groupId: string): Promise<ApiResult<Result<TaskTreeTimeline>>> => fetchJson(`/v1/tasktree/groups/${encodeURIComponent(groupId)}/timeline`, { timeoutMs: 12000, timeoutName: "TaskTree timeline" })
};
