/**
 * Formatage des dates presse en français.
 * Fichier sans dépendance DB pour pouvoir être importé côté client.
 */

const MOIS_FR = [
  "janvier", "février", "mars", "avril", "mai", "juin",
  "juillet", "août", "septembre", "octobre", "novembre", "décembre",
];

function toIsoDate(value: string | Date | null | undefined): string {
  if (value == null) return "";
  if (typeof value === "object" && "toISOString" in value) {
    return (value as Date).toISOString().slice(0, 10);
  }
  const s = String(value).trim();
  if (!s || s === "null" || s === "undefined") return "";
  const match = s.match(/^(\d{4})-(\d{2})-(\d{2})/);
  return match ? `${match[1]}-${match[2]}-${match[3]}` : s;
}

/** Formate une date ISO (YYYY-MM-DD) ou Date en français (ex. "15 janvier 2026"). */
export function formatDatePresse(
  isoDate: string | Date | null | undefined
): string {
  const s = toIsoDate(isoDate);
  if (!s) return "—";
  const [y, m, d] = s.split("-").map(Number);
  if (Number.isNaN(y) || Number.isNaN(m) || Number.isNaN(d)) return s;
  const month = MOIS_FR[m - 1];
  if (!month) return s;
  return `${d} ${month} ${y}`;
}
