/**
 * Formatos de presentación. Internamente las fechas viajan en ISO 8601 (UTC);
 * en pantalla se muestran en hora de Lima.
 */

export type CurrencyCode = "USD" | "PEN";

const CURRENCY_PREFIX: Record<CurrencyCode, string> = {
  USD: "US$",
  PEN: "S/",
};

/** 24900 / "24900.00" → "US$ 24,900"; "89900.5" → "S/ 89,900.50". */
export function formatMoney(amount: string | number, currency: CurrencyCode): string {
  const value = typeof amount === "number" ? amount : Number(amount);
  if (!Number.isFinite(value)) return "—";
  const hasCents = Math.round(value * 100) % 100 !== 0;
  const formatted = new Intl.NumberFormat("en-US", {
    minimumFractionDigits: hasCents ? 2 : 0,
    maximumFractionDigits: hasCents ? 2 : 0,
  }).format(value);
  return `${CURRENCY_PREFIX[currency]} ${formatted}`;
}

/** 18450 → "18,450 km" */
export function formatKm(km: number): string {
  return `${new Intl.NumberFormat("en-US").format(km)} km`;
}

export const APP_TIME_ZONE = "America/Lima";

/** Fecha → "DD/MM/YYYY" en hora de Lima. */
export function formatDate(date: Date | string): string {
  const d = typeof date === "string" ? new Date(date) : date;
  const parts = new Intl.DateTimeFormat("en-GB", {
    timeZone: APP_TIME_ZONE,
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  }).formatToParts(d);
  const get = (type: Intl.DateTimeFormatPartTypes): string =>
    parts.find((part) => part.type === type)?.value ?? "";
  return `${get("day")}/${get("month")}/${get("year")}`;
}

/** Fecha y hora → "DD/MM/YYYY HH:mm" en hora de Lima. */
export function formatDateTime(date: Date | string): string {
  const d = typeof date === "string" ? new Date(date) : date;
  const time = new Intl.DateTimeFormat("en-GB", {
    timeZone: APP_TIME_ZONE,
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  }).format(d);
  return `${formatDate(d)} ${time}`;
}
