import type { Project, Feature, Task, WorkLog, ProjectStats } from "./types";

const BASE = "/api";

async function request<T>(path: string, opts?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE}${path}`, {
    headers: { "Content-Type": "application/json" },
    ...opts,
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error(body.error || `HTTP ${res.status}`);
  }
  return res.json();
}

// Projects
export const listProjects = () => request<Project[]>("/projects");
export const createProject = (id: string, path: string) =>
  request<Project>("/projects", {
    method: "POST",
    body: JSON.stringify({ id, path }),
  });
export const getProject = (id: string) => request<Project>(`/projects/${id}`);
export const getProjectStats = (id: string) =>
  request<ProjectStats>(`/projects/${id}/stats`);

// Features
export const listFeatures = (projectId: string, status?: string) => {
  const params = status ? `?status=${status}` : "";
  return request<Feature[]>(`/projects/${projectId}/features${params}`);
};
export const createFeature = (
  projectId: string,
  data: { name: string; description?: string; status?: string }
) =>
  request<Feature>(`/projects/${projectId}/features`, {
    method: "POST",
    body: JSON.stringify(data),
  });
export const updateFeature = (
  id: number,
  data: Partial<Pick<Feature, "name" | "description" | "status">>
) =>
  request<Feature>(`/features/${id}`, {
    method: "PUT",
    body: JSON.stringify(data),
  });
export const deleteFeature = (id: number) =>
  request<{ ok: boolean }>(`/features/${id}`, { method: "DELETE" });

// Tasks
export const listTasks = (
  projectId: string,
  status?: string,
  priority?: string
) => {
  const params = new URLSearchParams();
  if (status) params.set("status", status);
  if (priority) params.set("priority", priority);
  const qs = params.toString();
  return request<Task[]>(`/projects/${projectId}/tasks${qs ? `?${qs}` : ""}`);
};
export const createTask = (
  projectId: string,
  data: {
    title: string;
    description?: string;
    priority?: string;
    status?: string;
    commit_base?: string;
    commit_head?: string;
  }
) =>
  request<Task>(`/projects/${projectId}/tasks`, {
    method: "POST",
    body: JSON.stringify(data),
  });
export const updateTask = (
  id: number,
  data: Partial<Pick<Task, "title" | "description" | "priority" | "status" | "commit_base" | "commit_head">>
) =>
  request<Task>(`/tasks/${id}`, {
    method: "PUT",
    body: JSON.stringify(data),
  });
export const deleteTask = (id: number) =>
  request<{ ok: boolean }>(`/tasks/${id}`, { method: "DELETE" });

// Work logs
export const listWorkLogs = (projectId: string) =>
  request<WorkLog[]>(`/projects/${projectId}/logs`);
export const createWorkLog = (
  projectId: string,
  data: {
    task_id: number;
    summary: string;
    files_changed?: string;
    test_result?: string;
  }
) =>
  request<WorkLog>(`/projects/${projectId}/logs`, {
    method: "POST",
    body: JSON.stringify(data),
  });
