// Tiny typed fetch helpers used with TanStack Query.

export async function apiGet<T>(url: string): Promise<T> {
  const res = await fetch(url, { cache: "no-store" });
  if (!res.ok) throw new Error((await safeError(res)) || `GET ${url} failed`);
  return res.json() as Promise<T>;
}

export async function apiSend<T>(
  url: string,
  method: "POST" | "PATCH" | "DELETE",
  body?: unknown
): Promise<T> {
  const res = await fetch(url, {
    method,
    headers: body ? { "Content-Type": "application/json" } : undefined,
    body: body ? JSON.stringify(body) : undefined,
  });
  if (!res.ok) throw new Error((await safeError(res)) || `${method} ${url} failed`);
  return res.json().catch(() => ({})) as Promise<T>;
}

async function safeError(res: Response): Promise<string | null> {
  try {
    const data = await res.json();
    return (data as { error?: string }).error ?? null;
  } catch {
    return null;
  }
}
