import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getCmsProvider } from "@/lib/cms/provider";
import { getRequestCmsProvider } from "@/lib/cms/provider.server";

export async function generateStaticParams() {
  const posts = await getCmsProvider().listBlogPosts();
  return posts.map(({ slug }) => ({ slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const post = await (
    await getRequestCmsProvider()
  ).getBlogPost((await params).slug);
  return post
    ? { title: post.title, description: post.excerpt }
    : { title: "Article not found" };
}

export default async function BlogPostPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const post = await (
    await getRequestCmsProvider()
  ).getBlogPost((await params).slug);
  if (!post) notFound();

  return (
    <article className="article-page">
      <header className="article-header">
        <p className="eyebrow">{post.category}</p>
        <h1>{post.title}</h1>
        <p className="article-header__excerpt">{post.excerpt}</p>
        <div className="article-byline">
          <span>{post.author}</span>
          <span>Published {post.publishedAt}</span>
          <span>{post.readingMinutes} min read</span>
        </div>
      </header>
      <div className="article-body">
        {post.sections.map((section) => (
          <section key={section.heading}>
            <h2>{section.heading}</h2>
            <p>{section.body}</p>
          </section>
        ))}
        <aside className="boundary-note">
          This is local demonstration content, reviewed {post.reviewedAt}. It is
          not legal, financial, or transaction advice.
        </aside>
        <Link className="text-link return-link" href="/blogs">
          ← Back to all articles
        </Link>
      </div>
    </article>
  );
}
