import { db } from "@/lib/db";
import { blogPosts, categories, blogPostCategories } from "@/lib/db/schema";
import { eq, asc } from "drizzle-orm";
import { notFound } from "next/navigation";
import BlogPostForm from "@/components/admin/BlogPostForm";

export const dynamic = "force-dynamic";

export default async function EditBlogPostPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const post = (await db.select().from(blogPosts).where(eq(blogPosts.id, id)))[0];
  if (!post) return notFound();

  const allCategories = await db.select().from(categories).orderBy(asc(categories.sortOrder));
  const selectedRows = await db.select().from(blogPostCategories).where(eq(blogPostCategories.postId, id));
  const selectedCategoryIds = selectedRows.map((r) => r.categoryId);

  return (
    <div>
      <h2 className="text-lg font-semibold mb-4">Edit Blog Post</h2>
      <BlogPostForm initial={post} postId={post.id} allCategories={allCategories} initialCategoryIds={selectedCategoryIds} />
    </div>
  );
}
