import type { Metadata } from "next";
import { cleanExcerpt } from "@/lib/articles/excerpt";
import { notFound } from "next/navigation";
import ArticleDetailPage from "./ArticleDetailClient";
import type { Article } from "@/lib/articles/types";
import {
  getLegacyArticleBySlug,
  getLegacyRecentSlugs,
  getLegacyRelatedArticles,
  getRelatedForumThreads, type RelatedForumThread,
} from "@/lib/articles/legacy-source";

// Deleted or unpublished posts must 404 immediately — never serve a stale
// cached article shell for up to an hour after DB removal.
export const dynamic = "force-dynamic";
export const revalidate = 0;
export const dynamicParams = true;

interface PageProps {
  params: Promise<{ slug: string }>;
}

const SITE_URL =
  process.env.NEXT_PUBLIC_SITE_URL || "https://avbeat.com";

function toIso(d: string | null | undefined): string {
  if (!d) return new Date().toISOString();
  const parsed = new Date(d);
  return isNaN(parsed.getTime()) ? new Date().toISOString() : parsed.toISOString();
}

function absoluteImage(src: string | undefined | null): string {
  if (!src) return `${SITE_URL}/assets/images/article-placeholder.jpg`;
  if (/^https?:\/\//i.test(src)) return src;
  return `${SITE_URL}${src.startsWith("/") ? "" : "/"}${src}`;
}

async function loadArticle(slug: string): Promise<{
  article: Article | null;
  related: Article[];
  relatedForumThreads: RelatedForumThread[];
}> {
  const imported = await getLegacyArticleBySlug(slug);
  if (!imported) return { article: null, related: [], relatedForumThreads: [] };
  const [related, relatedForumThreads] = await Promise.all([
    getLegacyRelatedArticles(slug, imported.category, 3),
    getRelatedForumThreads(imported.title, 6),
  ]);
  return { article: imported, related, relatedForumThreads };
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const { article } = await loadArticle(slug);
  if (!article) {
    return { title: "Article Not Found", description: "The article you are looking for does not exist." };
  }
  const noindex = !!article.noindex;
  return {
    title: article.title,
    description: cleanExcerpt(article.excerpt),
    alternates: { canonical: `/articles/${article.slug}` },
    robots: noindex
      ? { index: false, follow: false, nocache: true, googleBot: { index: false, follow: false, noimageindex: true } }
      : undefined,
    other: noindex ? { "googlebot-news": "noindex" } : undefined,
    openGraph: {
      type: "article",
      title: article.title,
      description: cleanExcerpt(article.excerpt),
      url: `/articles/${article.slug}`,
      images: [{ url: article.image, width: 1200, height: 630, alt: article.alt }],
      authors: [article.author],
      publishedTime: article.date,
      tags: article.tags,
    },
    twitter: {
      card: "summary_large_image",
      title: article.title,
      description: cleanExcerpt(article.excerpt),
      images: [article.image],
      creator: "@AV Beat",
    },
  };
}

export async function generateStaticParams() {
  const recent = await getLegacyRecentSlugs(50);
  return recent.map((slug) => ({ slug }));
}

export default async function ArticlePage({ params }: PageProps) {
  const { slug } = await params;
  const { article, related, relatedForumThreads } = await loadArticle(slug);
  if (!article) {
    notFound();
  }

  const articleSchema = {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: article.title,
    description: cleanExcerpt(article.excerpt),
    image: [absoluteImage(article.image)],
    author: { "@type": "Person", name: article.author },
    publisher: {
      "@type": "Organization",
      name: "AV Beat",
      logo: { "@type": "ImageObject", url: `${SITE_URL}/assets/images/logo.png` },
    },
    datePublished: toIso(article.date),
    dateModified: new Date().toISOString(),
    mainEntityOfPage: { "@type": "WebPage", "@id": `${SITE_URL}/articles/${article.slug}` },
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(articleSchema) }}
      />
      <ArticleDetailPage article={article} relatedArticles={related} relatedForumThreads={relatedForumThreads} />
    </>
  );
}
