// frontend/lib/tasks/api.ts
import type {
  Folder,
  Person,
  Project,
  Risk,
  ScaffoldResult,
  Task,
  TaskComment,
} from "@/lib/types";

const J = { "Content-Type": "application/json" };
async function ok<T>(r: Response): Promise<T> {
  if (!r.ok) throw new Error(`${r.status} ${r.statusText}`);
  return r.json() as Promise<T>;
}

export const tasksApi = {
  people: () => fetch("/api/people").then((r) => ok<Person[]>(r)),

  tree: () => fetch("/api/tree").then((r) => ok<Folder[]>(r)),

  // area/project_id 없으면 전체 작업(top-level 중첩 트리) 반환.
  list: (p: { area?: "work" | "life"; project_id?: string; status?: string; assignee?: string } = {}) => {
    const q = new URLSearchParams(
      Object.entries(p).filter(([, v]) => v != null) as [string, string][],
    );
    const qs = q.toString();
    return fetch(`/api/tasks${qs ? `?${qs}` : ""}`).then((r) => ok<Task[]>(r));
  },

  get: (id: string) => fetch(`/api/tasks/${id}`).then((r) => ok<Task>(r)),

  create: (body: Partial<Task> & { title: string; project_id: string }) =>
    fetch("/api/tasks", { method: "POST", headers: J, body: JSON.stringify(body) }).then((r) =>
      ok<Task>(r),
    ),

  patch: (id: string, body: Partial<Task>) =>
    fetch(`/api/tasks/${id}`, { method: "PATCH", headers: J, body: JSON.stringify(body) }).then(
      (r) => ok<Task>(r),
    ),

  remove: (id: string) => fetch(`/api/tasks/${id}`, { method: "DELETE" }).then((r) => r.ok),

  addComment: (id: string, body: { person_id: string; text: string }) =>
    fetch(`/api/tasks/${id}/comments`, { method: "POST", headers: J, body: JSON.stringify(body) }).then(
      (r) => ok<TaskComment>(r),
    ),

  scaffold: (id: string, body: { create?: boolean; use_llm?: boolean } = {}) =>
    fetch(`/api/tasks/${id}/scaffold`, { method: "POST", headers: J, body: JSON.stringify(body) }).then(
      (r) => ok<ScaffoldResult>(r),
    ),

  risks: (area: "work" | "life" = "work") =>
    fetch(`/api/risks?area=${area}`).then((r) => ok<Risk[]>(r)),

  createProject: (body: { folder_id: string; parent_id?: string; name: string; tone?: string }) =>
    fetch("/api/projects", { method: "POST", headers: J, body: JSON.stringify(body) }).then((r) =>
      ok<Project>(r),
    ),

  pinProject: (id: string) =>
    fetch(`/api/projects/${id}/pin`, { method: "POST" }).then((r) => ok<Project>(r)),
};
