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

import BlogArticle, { type BlogArticleViewData } from "@/views/BlogArticle";
import JsonLd from "@/components/seo/JsonLd";
import { SITE_URL } from "@/lib/seo";
import { wpSeoToMetadata, breadcrumbJsonLd } from "@/lib/wp/seoToMetadata";
import { mapImage } from "@/lib/wp/mappers";
import { getWpPost, getAllPostSlugs, getRelatedPosts, type WpPost } from "@/lib/wp/queries/post";
import { processArticleContent, formatFrDate, toBlogCard, FALLBACK_IMAGE } from "@/lib/blog/content";

// Articles publiés au build ; les nouveaux articles rendent à la demande (ISR).
export const dynamicParams = true;

export async function generateStaticParams(): Promise<{ slug: string }[]> {
  try {
    const slugs = await getAllPostSlugs();
    return slugs.map((slug) => ({ slug }));
  } catch (error) {
    console.error("[wp] énumération des articles indisponible :", error);
    return [];
  }
}

async function mapPost(post: WpPost): Promise<BlogArticleViewData> {
  const { html, toc, readTime } = processArticleContent(post.content);
  const category = post.categories?.nodes?.[0]?.name ?? "Ressources";
  const related = (await getRelatedPosts(category, post.slug, 3)).map(toBlogCard);
  const image = mapImage(post.featuredImage) ?? FALLBACK_IMAGE;

  return {
    slug: post.slug,
    title: post.title ?? "",
    description: post.seo?.metaDescription ?? "",
    category,
    date: formatFrDate(post.date),
    readTime,
    author: post.author?.node?.name ?? "Covalba",
    image,
    imageAlt: mapImage(post.featuredImage)?.altText || post.title || "",
    enBref: (post.article?.enBref ?? []).map((e) => e.point ?? "").filter(Boolean),
    contentHtml: html,
    toc,
    sources: (post.article?.bibliographie ?? [])
      .map((s) => ({ reference: s.reference ?? "", url: s.url ?? "" }))
      .filter((s) => s.reference || s.url),
    related,
  };
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  try {
    const post = await getWpPost(slug);
    if (!post) return {};
    return wpSeoToMetadata(post.seo, {
      title: post.title ? `${post.title} | Covalba` : undefined,
      description: post.excerpt ?? undefined,
      canonical: `${SITE_URL}/blog/${slug}`,
    });
  } catch {
    return {};
  }
}

export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;

  let post: WpPost | null = null;
  try {
    post = await getWpPost(slug);
  } catch (error) {
    console.error("[wp] article indisponible pour", slug, error);
    notFound();
  }
  if (!post) notFound();

  const article = await mapPost(post);
  const canonical = `${SITE_URL}/blog/${slug}`;

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    inLanguage: "fr-FR",
    headline: post.title,
    description: post.seo?.metaDescription ?? post.excerpt ?? "",
    ...(article.image ? { image: [article.image.sourceUrl] } : {}),
    datePublished: post.date,
    dateModified: post.modified ?? post.date,
    articleSection: article.category,
    author: { "@type": "Person", name: article.author },
    publisher: {
      "@type": "Organization",
      name: "Covalba",
      logo: { "@type": "ImageObject", url: `${SITE_URL}/logo-covalba.svg` },
    },
    mainEntityOfPage: canonical,
  };

  return (
    <>
      <JsonLd id="blog-article-jsonld" data={jsonLd} />
      <JsonLd
        id="blog-article-breadcrumb"
        data={breadcrumbJsonLd([
          { name: "Accueil", url: `${SITE_URL}/` },
          { name: "Guides", url: `${SITE_URL}/guides` },
          { name: post.title ?? slug, url: canonical },
        ])}
      />
      <BlogArticle article={article} />
    </>
  );
}
