import { roundMoneyForDisplay } from '../utils/roundMoneyForDisplay';

export type ResolvedCurrencyAmount = {
  accessibleLabel: string;
  parts: Intl.NumberFormatPart[];
};

export function createCurrencyFormatter(currency: string) {
  return new Intl.NumberFormat('es-MX', {
    style: 'currency',
    currency,
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

export function resolveCurrencyAmount(
  value: number | string | null | undefined,
  formatter: Intl.NumberFormat,
): ResolvedCurrencyAmount | null {
  if (value == null) {
    return null;
  }

  if (typeof value === 'string' && value.trim() === '') {
    return null;
  }

  const numeric = Number(value);
  if (!Number.isFinite(numeric)) {
    return null;
  }

  const rounded = roundMoneyForDisplay(numeric, 2);

  return {
    accessibleLabel: formatter.format(rounded),
    parts: formatter
      .formatToParts(rounded)
      .filter(part => part.type !== 'decimal'),
  };
}
