import { createDefaultSceneData } from "@/lib/project-defaults";
import type { ProjectType } from "@/lib/projects";

export type CreateVideoProjectResult =
  | { ok: true; projectId: string }
  | { ok: false; error: string };

export async function createVideoProject(input?: {
  name?: string;
  presetId?: string;
  initialSceneName?: string;
}): Promise<CreateVideoProjectResult> {
  const scene_data: Record<string, unknown> = {
    ...createDefaultSceneData("video"),
    ...(input?.presetId ? { templateId: input.presetId } : {}),
  };

  if (input?.initialSceneName) {
    const scenes = scene_data.scenes;
    if (Array.isArray(scenes) && scenes[0] && typeof scenes[0] === "object") {
      const first = scenes[0] as Record<string, unknown>;
      first.name = input.initialSceneName;
    }
  }

  const response = await fetch("/api/projects", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      type: "video" satisfies ProjectType,
      name: input?.name ?? undefined,
      scene_data,
    }),
  });

  const data = (await response.json()) as {
    project?: { id: string };
    error?: string;
    code?: string;
  };

  if (!response.ok || !data.project) {
    const message =
      data.code === "SUPABASE_NOT_CONFIGURED"
        ? "Supabase is not configured. Add your keys to .env.local."
        : (data.error ?? "Could not create project");
    return { ok: false, error: message };
  }

  return { ok: true, projectId: data.project.id };
}
