// frontend/lib/calendar/api.ts — calendarApi (week/day/meeting/materialize/focus)
import type { WeekBundle, DayBundle, Meeting, MaterializeResult, FocusBlock } from "./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 calendarApi = {
  week: () => fetch("/api/calendar/week", { cache: "no-store" }).then((r) => ok<WeekBundle>(r)),

  day: (d: number) =>
    fetch(`/api/calendar/day/${d}`, { cache: "no-store" }).then((r) => ok<DayBundle>(r)),

  meeting: (id: string) =>
    fetch(`/api/calendar/meetings/${id}`, { cache: "no-store" }).then((r) => ok<Meeting>(r)),

  materialize: (mid: string, idx: number) =>
    fetch(`/api/calendar/meetings/${mid}/actions/${idx}/materialize`, { method: "POST" }).then(
      (r) => ok<MaterializeResult>(r),
    ),

  materializeAll: (mid: string) =>
    fetch(`/api/calendar/meetings/${mid}/actions/materialize-all`, { method: "POST" }).then((r) =>
      ok<MaterializeResult[]>(r),
    ),

  focusSuggest: (day: number, min_minutes = 20, create = false) =>
    fetch("/api/calendar/focus/suggest", {
      method: "POST",
      headers: J,
      body: JSON.stringify({ day, min_minutes, create }),
    }).then((r) => ok<{ day: number; suggestions: FocusBlock[]; created: boolean }>(r)),
};
