// frontend/lib/approvals/api.ts
import type { ApprovalOut, ApprovalQueue, Autonomy } 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 approvalsApi = {
  queue: () => fetch("/api/approvals", { cache: "no-store" }).then((r) => ok<ApprovalQueue>(r)),

  setAutonomy: (level: Autonomy) =>
    fetch("/api/approvals/autonomy", {
      method: "PATCH",
      headers: J,
      body: JSON.stringify({ level }),
    }).then((r) => ok<{ level: Autonomy }>(r)),

  approve: (id: string) =>
    fetch(`/api/approvals/${id}/approve`, { method: "POST" }).then((r) => ok<ApprovalOut>(r)),

  undo: (id: string) =>
    fetch(`/api/approvals/${id}/undo`, { method: "POST" }).then((r) => ok<ApprovalOut>(r)),

  approveAll: () =>
    fetch("/api/approvals/approve-all", { method: "POST" }).then((r) => ok<{ approved: number }>(r)),
};
