import type { Metadata } from "next";
import { notFound, permanentRedirect } from "next/navigation";
import { SitePage } from "@/app/(site)/_components/SitePage";
import { SiteHeader } from "@/app/(site)/_components/SiteHeader";
import { SiteFooter } from "@/app/(site)/_components/SiteFooter";
import { ArticleView } from "@/app/(site)/_components/articles/ArticleView";
import { articleHref, isArticleSlug } from "@/app/(site)/_lib/articles";
import { getArticle, getArticles } from "@/app/(site)/_lib/cms";

type Props = { params: Promise<{ slug: string }> };

/**
 * Articles on the website when the site is built; newer ones render on their first visit.
 * Cache Components needs at least one entry: with no article yet, a placeholder that is
 * never a real slug (it renders the not-found page).
 */
export async function generateStaticParams() {
  const slugs: string[] = [];
  for (let page = 1; page <= 20; page++) {
    const list = await getArticles(`limit=24&page=${page}`);
    if (!list) break;
    slugs.push(...list.items.map((a) => a.slug));
    if (page >= list.totalPages) break;
  }
  return (slugs.length ? slugs : ["_"]).map((slug) => ({ slug }));
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const a = isArticleSlug(slug) ? await getArticle(slug) : null;
  if (!a) return {};
  // seo falls back to the title and excerpt.
  const title = `${a.seo?.title || a.title} — Unionists Group`;
  const description = a.seo?.description || a.excerpt || undefined;
  return {
    title,
    description,
    alternates: { canonical: articleHref(a.slug) },
    openGraph: { type: "article", title, description, publishedTime: a.publishedAt ?? undefined, images: a.coverImage?.url ? [a.coverImage.url] : undefined },
  };
}

export default async function Page({ params }: Props) {
  const { slug } = await params;
  const a = isArticleSlug(slug) ? await getArticle(slug) : null;
  if (!a) notFound();
  // An old slug: the API answered for the article's current one (proxy.ts normally redirects first).
  if (a.slug !== slug) permanentRedirect(articleHref(a.slug));

  return (
    <SitePage>
      <a className="skip-link" href="#main">
        Skip to main content
      </a>{" "}
      <SiteHeader active="/roadmap" activeItem="/thought-leadership-articles" />
      <main id="main" lang={a.language && a.language !== "en" ? a.language : undefined}>
        <ArticleView a={a} />
      </main>
      <SiteFooter />
    </SitePage>
  );
}
