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

export const dynamic = "force-dynamic";

interface Props { params: Promise<{ id: string }> }

export default async function EditPostPage({ params }: Props) {
  const session = await getSession();
  if (!session.isLoggedIn) redirect("/admin/login");

  const { id } = await params;
  const post = await prisma.post.findUnique({
    where: { id },
    include: { tags: { include: { tag: true } } },
  });
  if (!post) notFound();

  const initialData = {
    id: post.id,
    title: post.title,
    slug: post.slug,
    locale: post.locale,
    category: post.category,
    excerpt: post.excerpt ?? "",
    body: post.body ?? "",
    coverImage: post.coverImage ?? "",
    featured: post.featured,
    publishedAt: post.publishedAt.toISOString().split("T")[0],
    seoTitle: post.seoTitle ?? "",
    seoDesc: post.seoDesc ?? "",
    tagIds: post.tags.map((pt) => pt.tag.id),
  };

  return (
    <div>
      <div className="mb-6">
        <a href="/admin/posts" className="text-sm text-text-secondary hover:text-accent">← برگشت به نوشته‌ها</a>
        <h1 className="mt-2 text-2xl font-bold text-text-primary">ویرایش نوشته</h1>
        <p className="text-sm text-text-secondary font-mono mt-1">/{post.slug}</p>
      </div>
      <PostForm initialData={initialData} />
    </div>
  );
}
