import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getBlogPostBySlug } from "@/app/lib/blogs";
import { buildArticleMetadata, noIndexMetadata } from "@/app/lib/seo";
import { PageBreadcrumbJsonLd, PostArticleJsonLd } from "@/app/markup/seo/json-ld";
import { BlogDetail } from "../../markup/sections/blog-detail";

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

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const { data } = await getBlogPostBySlug(slug);
  // Nothing to describe, and it must not be indexed as a real article.
  if (!data) return { ...noIndexMetadata, title: "Article not found | Oxyfinz" };

  return buildArticleMetadata({
    seo: data.seo,
    path: `/blogs/${data.slug}`,
    fallbackTitle: data.title,
    fallbackDescription: data.excerpt,
    fallbackImage: data.image,
  });
}

export default async function BlogDetailPage({ params }: PageProps) {
  const { slug } = await params;
  const { data, error, notFound: isMissing } = await getBlogPostBySlug(slug);

  if (isMissing) {
    notFound();
  }

  if (error || !data) {
    return (
      <section className="wwd-section blog-detail-section">
        <div className="wwd-inner blog-detail-inner" style={{ textAlign: "center" }}>
          <p className="blogs-empty">{error || "Unable to load this article right now."}</p>
          <Link
            href={`/blogs/${encodeURIComponent(slug)}`}
            data-oxy-href={`/blogs/${encodeURIComponent(slug)}`}
            className="blog-back-link"
            style={{ justifyContent: "center" }}
          >
            Try again
          </Link>
        </div>
      </section>
    );
  }

  return (
    <>
      <PageBreadcrumbJsonLd path={`/blogs/${data.slug}`} name={data.title} />
      <PostArticleJsonLd
        path={`/blogs/${data.slug}`}
        headline={data.title}
        description={data.excerpt}
        image={data.image}
        datePublished={data.date_added}
        dateModified={data.last_updated}
        isBlogPost={data.f_type === "B"}
      />
      <BlogDetail post={data} />
    </>
  );
}
