import type { UserProjectsSnapshot } from "@/lib/storage/projects";

export async function fetchUserProjects(): Promise<UserProjectsSnapshot | null> {
  const res = await fetch("/api/projects");
  if (res.status === 401) return null;
  if (!res.ok) throw new Error("Failed to load projects");

  const data = (await res.json()) as {
    snapshot: UserProjectsSnapshot & { updatedAt: string | null };
  };

  return {
    activeProjectId: data.snapshot.activeProjectId ?? null,
    projects: data.snapshot.projects ?? [],
    dataByProjectId: data.snapshot.dataByProjectId ?? {},
    updatedAt: data.snapshot.updatedAt ?? new Date().toISOString(),
  };
}

export async function saveUserProjects(snapshot: Omit<UserProjectsSnapshot, "updatedAt">) {
  const res = await fetch("/api/projects", {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(snapshot),
  });

  if (res.status === 401) throw new Error("Unauthorized");
  if (!res.ok) {
    const data = (await res.json()) as { error?: string };
    throw new Error(data.error ?? "Failed to save projects");
  }

  return res.json();
}
