// Conversion du groupe SEO WordPress (clone_seo) vers la Metadata API Next.
// Utilisé par toutes les routes branchées sur WP (CPT + pages one-off).

import type { Metadata } from "next";
import type { WpSeo } from "./types";
import { mapImage } from "./mappers";
import { OG_LOCALE, type Locale } from "@/config/i18nRoutes";

export interface WpSeoFallbackImage {
  url: string;
  width?: number | null;
  height?: number | null;
  alt?: string | null;
}

export interface WpSeoFallback {
  title?: string;
  description?: string;
  canonical?: string;
  image?: WpSeoFallbackImage;
}

/**
 * Construit la Metadata Next depuis le champ `seo` WordPress, avec fallback
 * champ par champ (metas historiques en dur, canonical par défaut, etc.).
 * `locale` pilote og:locale (code neutre fr/en/es, jamais de territoire).
 */
export function wpSeoToMetadata(
  seo: WpSeo | null | undefined,
  fallback: WpSeoFallback = {},
  locale: Locale = "fr"
): Metadata {
  const title = seo?.titreSeo || fallback.title;
  const description = seo?.metaDescription || fallback.description;
  const canonical = seo?.canonical || fallback.canonical;
  const ogImage = mapImage(seo?.ogImage);
  const fallbackImage = fallback.image;
  const image = ogImage
    ? {
        url: ogImage.sourceUrl,
        width: ogImage.width,
        height: ogImage.height,
        alt: ogImage.altText,
      }
    : fallbackImage;

  return {
    ...(title ? { title } : {}),
    ...(description ? { description } : {}),
    ...(canonical ? { alternates: { canonical } } : {}),
    ...(seo?.noindex ? { robots: { index: false, follow: false } } : {}),
    openGraph: {
      ...(title ? { title } : {}),
      ...(description ? { description } : {}),
      ...(canonical ? { url: canonical } : {}),
      type: "website",
      locale: OG_LOCALE[locale],
      ...(image
        ? {
            images: [
              {
                url: image.url,
                ...(image.width ? { width: image.width } : {}),
                ...(image.height ? { height: image.height } : {}),
                ...(image.alt ? { alt: image.alt } : {}),
              },
            ],
          }
        : {}),
    },
    twitter: {
      ...(title ? { title } : {}),
      ...(description ? { description } : {}),
      ...(image
        ? { card: "summary_large_image" as const, images: [image.url] }
        : {}),
    },
  };
}

/** Schéma BreadcrumbList JSON-LD (systématique sur les pages WP-driven). */
export function breadcrumbJsonLd(items: { name: string; url: string }[]) {
  return {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: items.map((item, index) => ({
      "@type": "ListItem",
      position: index + 1,
      name: item.name,
      item: item.url,
    })),
  };
}
