import type { Locale } from "@/shared/i18n/config";

const LOCALE_TO_BCP47: Record<Locale, string> = {
  fr: "fr-FR",
  en: "en-US",
};

export function formatDate(value: string | number | Date, locale: Locale): string {
  return new Date(value).toLocaleDateString(LOCALE_TO_BCP47[locale]);
}

export function formatDateTime(value: string | number | Date, locale: Locale): string {
  return new Date(value).toLocaleString(LOCALE_TO_BCP47[locale]);
}

const RELATIVE_UNITS: { unit: Intl.RelativeTimeFormatUnit; seconds: number }[] = [
  { unit: "year", seconds: 31_536_000 },
  { unit: "month", seconds: 2_592_000 },
  { unit: "week", seconds: 604_800 },
  { unit: "day", seconds: 86_400 },
  { unit: "hour", seconds: 3_600 },
  { unit: "minute", seconds: 60 },
  { unit: "second", seconds: 1 },
];

export function formatRelative(value: string | number | Date, locale: Locale): string {
  const target = new Date(value).getTime();
  const diffSec = Math.round((target - Date.now()) / 1000);
  const rtf = new Intl.RelativeTimeFormat(LOCALE_TO_BCP47[locale], { numeric: "auto" });
  const abs = Math.abs(diffSec);
  for (const { unit, seconds } of RELATIVE_UNITS) {
    if (abs >= seconds) return rtf.format(Math.round(diffSec / seconds), unit);
  }
  return rtf.format(0, "second");
}
