import type { ProjectStatus, ProjectType } from "@/lib/projects";

export interface ProjectDetail {
  id: string;
  name: string;
  type: ProjectType;
  scene_data: Record<string, unknown>;
  status: ProjectStatus;
  updated_at: string;
}

export interface ProjectApiResponse {
  project: ProjectDetail;
}

export class ProjectApiError extends Error {
  readonly status: number;

  constructor(message: string, status: number) {
    super(message);
    this.name = "ProjectApiError";
    this.status = status;
  }
}

export function isProjectApiError(error: unknown): error is ProjectApiError {
  return error instanceof ProjectApiError;
}

export function isProjectNotFoundError(error: unknown): boolean {
  return isProjectApiError(error) && error.status === 404;
}

async function parseProjectResponse(
  response: Response
): Promise<ProjectApiResponse & { error?: string }> {
  return (await response.json()) as ProjectApiResponse & { error?: string };
}

export async function fetchProject(
  projectId: string
): Promise<ProjectApiResponse> {
  const response = await fetch(`/api/projects/${projectId}`, {
    method: "GET",
    cache: "no-store",
  });

  const data = await parseProjectResponse(response);

  if (!response.ok) {
    throw new ProjectApiError(data.error ?? "Failed to load project", response.status);
  }

  return data;
}

export async function patchProjectSceneData(
  projectId: string,
  scene_data: Record<string, unknown>
): Promise<ProjectApiResponse> {
  const response = await fetch(`/api/projects/${projectId}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ scene_data }),
  });

  const data = await parseProjectResponse(response);

  if (!response.ok) {
    throw new ProjectApiError(data.error ?? "Failed to save project", response.status);
  }

  return data;
}
