// frontend/lib/inbox/api.ts
import type { CaptureResult, ConfirmResult, InboxItem, RouteType } from "@/lib/types";

const BASE = process.env.NEXT_PUBLIC_API_BASE ?? "http://localhost:31800";

export class ApiError extends Error {
  constructor(
    public status: number,
    public body: string,
  ) {
    super(`API ${status}`);
  }
}

async function j<T>(res: Response): Promise<T> {
  if (!res.ok) throw new ApiError(res.status, await res.text());
  return res.json() as Promise<T>;
}

export async function getInbox(): Promise<InboxItem[]> {
  return j(await fetch(`${BASE}/api/inbox`, { cache: "no-store" }));
}

export async function captureInbox(input: {
  kind: "text" | "voice" | "image";
  raw: string;
}): Promise<CaptureResult> {
  return j(
    await fetch(`${BASE}/api/inbox/capture`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(input),
    }),
  );
}

export async function reclassifyInbox(id: string, type?: RouteType): Promise<CaptureResult> {
  return j(
    await fetch(`${BASE}/api/inbox/${id}/reclassify`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(type ? { type } : {}),
    }),
  );
}

export async function confirmInbox(id: string): Promise<ConfirmResult> {
  return j(await fetch(`${BASE}/api/inbox/${id}/confirm`, { method: "POST" }));
}

export async function dismissInbox(id: string): Promise<InboxItem> {
  return j(await fetch(`${BASE}/api/inbox/${id}/dismiss`, { method: "POST" }));
}
