// Formatting helpers for statutory-style financial reports (docs/21-GENERAL-LEDGER-FRONTEND.md) —
// comma-grouped thousands, fixed 2 decimals, negatives in parentheses (standard financial-statement
// convention), rather than the plain `.toFixed(2)` used by the inventory-side stock screens.

const AMOUNT_FORMATTER = new Intl.NumberFormat("en-US", {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
})

/** `1234.5` -> "1,234.50"; `-1234.5` -> "(1,234.50)"; `0`/`null`/`undefined` -> the given fallback. */
export function formatAmount(value: number | null | undefined, zeroDash = false): string {
  if (value === null || value === undefined || Number.isNaN(value)) return "—"
  if (zeroDash && value === 0) return "—"
  const formatted = AMOUNT_FORMATTER.format(Math.abs(value))
  return value < 0 ? `(${formatted})` : formatted
}

/** `"2026-07-01"` / an ISO timestamp -> "01 Jul 2026" for report headers and tables. */
export function formatReportDate(value: string | null | undefined): string {
  if (!value) return "—"
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return date.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })
}

/** Today's date as `YYYY-MM-DD`, for default report filter values. */
export function todayIso(): string {
  return new Date().toISOString().slice(0, 10)
}

/** The first day of the current month as `YYYY-MM-DD`, for default period-start filter values. */
export function startOfMonthIso(): string {
  const now = new Date()
  return new Date(now.getFullYear(), now.getMonth(), 1).toISOString().slice(0, 10)
}
