import { notFound, redirect } from "next/navigation";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { ProjectForm } from "../ProjectForm";

export const dynamic = "force-dynamic";
interface Props { params: Promise<{ id: string }> }

export default async function EditProjectPage({ params }: Props) {
  const session = await getSession();
  if (!session.isLoggedIn) redirect("/admin/login");
  const { id } = await params;
  const project = await prisma.project.findUnique({ where: { id } });
  if (!project) notFound();

  function parseArr(val: string | null): string[] {
    if (!val) return [];
    try { return JSON.parse(val); } catch { return []; }
  }

  return (
    <div>
      <div className="mb-6">
        <a href="/admin/projects" className="text-sm text-text-secondary hover:text-accent">← برگشت به پروژه‌ها</a>
        <h1 className="mt-2 text-2xl font-bold text-text-primary">ویرایش پروژه</h1>
      </div>
      <ProjectForm initialData={{
        id: project.id, title: project.title, slug: project.slug,
        locale: project.locale, projectType: project.projectType,
        description: project.description ?? "", body: project.body ?? "",
        coverImage: project.coverImage ?? "", gallery: parseArr(project.gallery),
        techStack: parseArr(project.techStack), toolsUsed: parseArr(project.toolsUsed),
        liveUrl: project.liveUrl ?? "", githubUrl: project.githubUrl ?? "",
        featured: project.featured, sortOrder: project.sortOrder,
        seoTitle: project.seoTitle ?? "", seoDesc: project.seoDesc ?? "",
      }} />
    </div>
  );
}
