// Mappers : normalisent les sorties WPGraphQL avant rendu.

import type { WpImage, WpImageField } from "./types";

/** Origine des médias WordPress (cf. wordpress/SCHEMA.md + .env.example). */
const WP_MEDIA_ORIGIN = "https://covalba-admin.paf-studio.dev";

/**
 * Aplati un champ image GraphQL `{ node: { sourceUrl, altText, mediaDetails } }`.
 * Retourne null si l'image est absente (champ ACF vide).
 */
export function mapImage(field?: WpImageField | null): WpImage | null {
  const node = field?.node;
  if (!node?.sourceUrl) return null;
  return {
    sourceUrl: node.sourceUrl,
    altText: node.altText ?? "",
    width: node.mediaDetails?.width ?? null,
    height: node.mediaDetails?.height ?? null,
  };
}

/** Les repeaters/flexibles vides sortent null en GraphQL → toujours mapper vers []. */
export function arr<T>(v: T[] | null | undefined): T[] {
  return v ?? [];
}

export interface AccentSegment {
  text: string;
  accent: boolean;
}

/**
 * Découpe la convention `*accent*` d'un titre en segments.
 * Ex. "Toiture *plus fraîche*" → [{ text: "Toiture ", accent: false }, { text: "plus fraîche", accent: true }]
 * Les segments accent sont rendus en <span class="accent"> côté front.
 */
export function parseAccent(titre: string): AccentSegment[] {
  if (!titre) return [];
  const segments: AccentSegment[] = [];
  const re = /\*([^*]+)\*/g;
  let lastIndex = 0;
  let match: RegExpExecArray | null;
  while ((match = re.exec(titre)) !== null) {
    if (match.index > lastIndex) {
      segments.push({ text: titre.slice(lastIndex, match.index), accent: false });
    }
    segments.push({ text: match[1], accent: true });
    lastIndex = match.index + match[0].length;
  }
  if (lastIndex < titre.length) {
    segments.push({ text: titre.slice(lastIndex), accent: false });
  }
  return segments;
}

/**
 * Réécrit les URLs absolues des médias WordPress dans un HTML (wysiwyg).
 * Les URLs restent absolues ; seule l'origine change si NEXT_PUBLIC_WP_MEDIA_URL
 * est définie (CDN, proxy…). Sans cette variable, le HTML est retourné tel quel.
 */
export function rewriteWpUrls(html: string): string {
  if (!html) return html;
  const target = process.env.NEXT_PUBLIC_WP_MEDIA_URL;
  if (!target) return html;
  const normalized = target.replace(/\/+$/, "");
  return html.replaceAll(
    `${WP_MEDIA_ORIGIN}/wp-content/uploads`,
    `${normalized}/wp-content/uploads`
  );
}
