// frontend/lib/notify/api.ts — notifyApi (triage/guard/digests/senders + reclassify/undo)
import type {
  Digest,
  Notification,
  NotifyBucket,
  NotifyGuard,
  SenderRule,
  Triage,
} 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 notifyApi = {
  triage: () => fetch("/api/notifications", { cache: "no-store" }).then((r) => ok<Triage>(r)),

  guard: () =>
    fetch("/api/notifications/guard", { cache: "no-store" }).then((r) => ok<NotifyGuard>(r)),

  digests: () =>
    fetch("/api/notifications/digests", { cache: "no-store" }).then((r) => ok<Digest[]>(r)),

  senders: () =>
    fetch("/api/notifications/senders", { cache: "no-store" }).then((r) => ok<SenderRule[]>(r)),

  reclassify: (id: string, to_bucket: NotifyBucket) =>
    fetch(`/api/notifications/${id}/reclassify`, {
      method: "POST",
      headers: J,
      body: JSON.stringify({ to_bucket }),
    }).then((r) => ok<Notification>(r)),

  undo: (id: string) =>
    fetch(`/api/notifications/${id}/undo`, { method: "POST", headers: J, body: "{}" }).then((r) =>
      ok<Notification>(r),
    ),

  setGuard: (on: boolean) =>
    fetch("/api/notifications/guard", {
      method: "POST",
      headers: J,
      body: JSON.stringify({ on }),
    }).then((r) => ok<NotifyGuard>(r)),
};
