export function toNum(value: unknown): number | null {
  if (value === null || value === undefined) return null;
  if (typeof value === 'number') return Number.isFinite(value) ? value : null;

  const trimmed = String(value).trim();
  if (!trimmed) return null;

  const parsed = Number(trimmed);
  return Number.isFinite(parsed) ? parsed : null;
}

export function formatNumber(value: number | null | undefined, digits = 2, fallback = 'N/A') {
  if (value === null || value === undefined) return fallback;
  return value.toFixed(digits);
}

export function formatLocaleNumber(
  value: number | null | undefined,
  digits = 0,
  locale = 'en-AU',
  fallback = '-'
) {
  if (value === null || value === undefined) return fallback;
  return value.toLocaleString(locale, { maximumFractionDigits: digits });
}

export function formatDate(
  value: string | null | undefined,
  options: Intl.DateTimeFormatOptions = { dateStyle: 'medium' },
  locale = 'en-NZ',
  fallback = '-'
) {
  if (!value) return fallback;

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;

  return new Intl.DateTimeFormat(locale, options).format(date);
}
