// Mapper inverse : CPT `reference` WP → CustomerReference détaillée consommée
// par la vue d'origine (src/views/ReferenceDetail.tsx).
//
// Bijection inverse du mapping d'export (scripts/wp-seed/export-data.mts,
// buildReferenceDoc) :
//   seo.meta_description       → description
//   secteurs (taxonomie)       → sector
//   fiche_reference            → clientName / location / product / support /
//                                metrics / quote / videoUrls / showInGrid
//   section video              → videoUrls / videoTakeaways
//   section contenu_seo        → detailIntro / detailNarrative (paragraphes de
//                                l'intro) + detailSections
//   (fiche_chantier : simple interrupteur d'affichage, sans données propres)
//
// Champ WP manquant/vide → valeur de la CustomerReference codée (deep-merge
// champ à champ via getDetailedReferenceBySlug : la donnée WP prime, le codé
// comble).

import {
  getDetailedReferenceBySlug,
  sectorBySlug,
  type CustomerReference,
  type ReferenceSectorSlug,
} from "@/data/references";

import { arr } from "./mappers";
import { paragraphsOf, sectionsOf, str } from "./toRoofPageData";
import type { ContenuSeoBlock, VideoBlock, WpReference } from "./types";

export function toCustomerReference(ref: WpReference): CustomerReference {
  const slug = ref.slug ?? "";
  const fb: CustomerReference | undefined = getDetailedReferenceBySlug(slug);

  const sections = arr(ref.sections?.sections);
  const video = sectionsOf<VideoBlock>(sections, "VideoLayout")[0];
  const contenuSeo = sectionsOf<ContenuSeoBlock>(sections, "ContenuSeoLayout")[0];
  const fiche = ref.ficheReference;

  // Secteur : terme de taxonomie WP → libellé du front (sectorBySlug).
  const secteurSlug = ref.secteurs?.nodes?.[0]?.slug as
    | ReferenceSectorSlug
    | undefined;
  const sector =
    (secteurSlug && sectorBySlug[secteurSlug]) || fb?.sector || "Industrie";

  // Vidéos : fiche_reference.video_url + section video (dédupliquées).
  const videoUrls = [
    ...new Set([str(fiche?.videoUrl), str(video?.videoUrl)].filter(
      (url): url is string => Boolean(url)
    )),
  ];

  const videoTakeaways = arr(video?.pointsCles).length
    ? arr(video?.pointsCles).map((point) => ({
        label: point.label ?? "",
        text: point.texte ?? "",
      }))
    : undefined;

  const metrics = arr(fiche?.metrics).length
    ? arr(fiche?.metrics).map((metric) => ({
        value: metric.value ?? "",
        label: metric.label ?? "",
      }))
    : undefined;

  const quote = str(fiche?.quote?.texte)
    ? {
        text: fiche?.quote?.texte ?? "",
        author: str(fiche?.quote?.auteur) ?? undefined,
        role: str(fiche?.quote?.role) ?? undefined,
      }
    : fb?.quote;

  // L'export replie detailIntro + detailNarrative dans l'intro du contenu_seo
  // (un <p> chacun) : le premier paragraphe est l'intro, le second le récit.
  const introParagraphs = paragraphsOf(contenuSeo?.intro);
  const detailSections = arr(contenuSeo?.sections).length
    ? arr(contenuSeo?.sections).map((section) => ({
        title: section.titre ?? "",
        text: paragraphsOf(section.contenu).join("\n\n"),
      }))
    : undefined;

  return {
    id: fb?.id ?? slug,
    title: str(ref.title) ?? fb?.title ?? "",
    clientName: str(fiche?.clientName) ?? fb?.clientName ?? "",
    sector,
    description: str(ref.seo?.metaDescription) ?? fb?.description ?? "",
    // L'image de la fiche est la featured image WP, non exposée par la query
    // GraphQL actuelle → toujours comblée par la donnée codée.
    image: fb?.image,
    location: str(fiche?.location) ?? fb?.location,
    product: str(fiche?.produit?.nodes?.[0]?.title) ?? fb?.product,
    support: str(fiche?.support) ?? fb?.support,
    metrics: metrics ?? fb?.metrics,
    quote,
    sourceUrls: fb?.sourceUrls,
    videoUrls: videoUrls.length ? videoUrls : fb?.videoUrls,
    videoTakeaways: videoTakeaways ?? fb?.videoTakeaways,
    detailSlug: slug || fb?.detailSlug,
    detailIntro: introParagraphs[0] ?? fb?.detailIntro,
    detailNarrative: introParagraphs[1] ?? fb?.detailNarrative,
    detailSections: detailSections ?? fb?.detailSections,
    tags: fb?.tags,
    highlightSectors: fb?.highlightSectors,
    readiness: fb?.readiness ?? "phase-2-ready",
    showInGrid:
      typeof fiche?.showInGrid === "boolean"
        ? fiche.showInGrid
        : fb?.showInGrid ?? false,
  };
}
