import { db } from "@/db";
import { projects, categories } from "@/db/schema";
import { eq } from "drizzle-orm";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import ProjectDetailClient from "./ProjectDetailClient";

export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const [project] = await db
    .select()
    .from(projects)
    .where(eq(projects.slug, slug))
    .limit(1);

  if (!project) return { title: "Project Not Found" };

  return {
    title: `${project.title} — Samuel Adesanya`,
    description: project.shortDescription || project.description || "",
  };
}

export default async function ProjectPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const [project] = await db
    .select()
    .from(projects)
    .where(eq(projects.slug, slug))
    .limit(1);

  if (!project || !project.published) {
    notFound();
  }

  let category = null;
  if (project.categoryId) {
    const [cat] = await db
      .select()
      .from(categories)
      .where(eq(categories.id, project.categoryId))
      .limit(1);
    category = cat || null;
  }

  return <ProjectDetailClient project={project} category={category} />;
}
