import type { Metadata } from "next";
import { notFound } from "next/navigation";
import prisma from "@/server/db/prisma";
import ProjectDetailsClient from "./ProjectDetailsClient";

interface Project {
  id: number;
  name: string;
  description: string;
  coverImage: string;
  galleryImages: string[];
}

// Enable static generation with hourly revalidation
export const revalidate = 3600;

export const dynamic = "force-dynamic";

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
  const { id } = await params;
  const project = await prisma.project.findUnique({
    where: { id: Number(id) },
    include: {
      seometadata: true,
    },
  });

  if (!project) {
    return {
      title: "Project Not Found",
      description: "The requested project could not be found.",
    };
  }

  // Use SEO metadata from database if available, otherwise use project data
  const title = project.seometadata?.title || `${project.name} - Nitescape`;
  const description = project.seometadata?.metaDescription || project.description;
  const ogImage = project.seometadata?.ogImage || project.coverImage;

  return {
    title,
    description,
    openGraph: {
      title,
      description,
      images: ogImage ? [{ url: ogImage }] : [],
      type: "article",
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: ogImage ? [ogImage] : [],
    },
    alternates: {
      canonical: `https://nitescape.com/projects/${project.id}`,
    },
    robots: {
      index: true,
      follow: true,
    },
  };
}

async function getProject(id: string): Promise<Project | null> {
  const project = await prisma.project.findUnique({
    where: { id: Number(id) },
  });
  if (!project) return null;
  let galleryImages: string[] = [];
  if (Array.isArray(project.galleryImages)) {
    galleryImages = project.galleryImages as string[];
  } else if (typeof project.galleryImages === "string") {
    try {
      const parsed = JSON.parse(project.galleryImages);
      if (Array.isArray(parsed)) {
        galleryImages = parsed;
      }
    } catch {
      galleryImages = [];
    }
  }
  return {
    id: project.id,
    name: project.name,
    description: project.description,
    coverImage: project.coverImage || "",
    galleryImages,
  };
}

export default async function ProjectDetails({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const project = await getProject(id);
  if (!project) {
    notFound();
  }
  return <ProjectDetailsClient project={project} />;
}
