import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { AdminPageHeader } from "@/components/admin/page-header";
import { ProjectForm, ProjectFormValues } from "@/components/admin/project-form";

export const dynamic = "force-dynamic";

function parseArray(json: string | null | undefined): string[] {
  try {
    const arr = JSON.parse(json || "[]");
    if (Array.isArray(arr)) return arr.filter((x) => typeof x === "string");
  } catch {}
  return [];
}

export default async function EditProjectPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const p = await db.project.findUnique({ where: { id } });
  if (!p) notFound();

  const initial: ProjectFormValues = {
    id: p.id,
    title: p.title,
    slug: p.slug,
    description: p.description,
    content: p.content,
    category: p.category || "Commercial",
    location: p.location || "",
    completionDate: p.completionDate || "",
    client: p.client || "",
    images: parseArray(p.images),
    videos: parseArray(p.videos),
    isFeatured: p.isFeatured,
    isEnabled: p.isEnabled,
    metaTitle: p.metaTitle || "",
    metaDescription: p.metaDescription || "",
  };

  return (
    <>
      <AdminPageHeader title="Edit Project" description={p.title} />
      <ProjectForm initial={initial} />
    </>
  );
}
