import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { AdminPageHeader } from "@/components/admin/page-header";
import { BlogForm, BlogFormValues } from "@/components/admin/blog-form";

export const dynamic = "force-dynamic";

function parseTags(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 EditBlogPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const p = await db.blogPost.findUnique({ where: { id } });
  if (!p) notFound();

  const initial: BlogFormValues = {
    id: p.id,
    title: p.title,
    slug: p.slug,
    excerpt: p.excerpt,
    content: p.content,
    category: p.category || "",
    tags: parseTags(p.tags),
    featuredImage: p.featuredImage,
    isPublished: p.isPublished,
    publishedAt: p.publishedAt ? p.publishedAt.toISOString() : "",
    authorName: p.authorName || "",
    metaTitle: p.metaTitle || "",
    metaDescription: p.metaDescription || "",
  };

  return (
    <>
      <AdminPageHeader title="Edit Blog Post" description={p.title} />
      <BlogForm initial={initial} />
    </>
  );
}
