import { decodeJsonError } from "../../cardRuntime/api";

function nextLocalMidnightIso(): string {
  const tomorrow = new Date();
  tomorrow.setHours(24, 0, 0, 0);
  return tomorrow.toISOString();
}

export async function snoozeCardUntilTomorrow(cardId: string | null | undefined): Promise<void> {
  const key = (cardId || "").trim();
  if (!key) throw new Error("card id is required");
  const resp = await fetch(`/cards/${encodeURIComponent(key)}/snooze`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ until: nextLocalMidnightIso() }),
  });
  if (!resp.ok) throw new Error(await decodeJsonError(resp));
  window.dispatchEvent(new Event("nanobot:cards-refresh"));
}
