import type { Metadata } from "next";
import { notFound } from "next/navigation";

import { NewsArticleDetail } from "@/components/news/NewsArticleDetail";
import { SiteFooter } from "@/components/SiteFooter";
import { SiteHeader } from "@/components/SiteHeader";
import { getBlogs, toDisplayNewsItem } from "@/lib/api";

export const revalidate = 3600;

async function getBlogPosts() {
  const posts = await getBlogs();
  return posts.filter((p) => p.type !== "news");
}

export async function generateStaticParams() {
  const posts = await getBlogPosts();
  return posts.map((item) => ({ slug: item.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const posts = await getBlogPosts();
  const item = posts.find((p) => p.slug === slug);
  if (!item) return {};
  return { title: item.titleFa || item.title, description: item.abstract || item.titleFa };
}

export default async function BlogDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const posts = await getBlogPosts();
  const item = posts.find((p) => p.slug === slug);
  if (!item) notFound();

  return (
    <>
      <SiteHeader />
      <main>
        <NewsArticleDetail item={toDisplayNewsItem(item)} basePath="/blog" sectionLabel="بلاگ" />
      </main>
      <SiteFooter />
    </>
  );
}
