import Decimal from 'decimal.js';

// One Money type across backend and both frontends. JS `number` is a float and
// must NEVER hold money — that was the legacy system's #1 correctness bug.
// Persisted as DECIMAL(14,2) in MySQL; carried as decimal.js everywhere in code.

Decimal.set({ precision: 34, rounding: Decimal.ROUND_HALF_UP });

export { Decimal };
export type MoneyInput = Decimal.Value;

export const money = (v: MoneyInput = 0): Decimal => new Decimal(v);
export const ZERO = new Decimal(0);

export const sum = (values: readonly MoneyInput[]): Decimal =>
  values.reduce<Decimal>((acc, v) => acc.plus(v), new Decimal(0));

export const isZero = (v: MoneyInput): boolean => new Decimal(v).isZero();
export const isNegative = (v: MoneyInput): boolean => new Decimal(v).isNegative();

/** Round to cents (2dp, half-up) — the canonical persisted form. */
export const toCents = (v: MoneyInput): Decimal => new Decimal(v).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
export const toFixed2 = (v: MoneyInput): string => new Decimal(v).toFixed(2);

/** Format for display, e.g. formatMoney('1234.5', 'HK$') -> "HK$1,234.50" */
export const formatMoney = (v: MoneyInput, symbol = ''): string => {
  const [int = '0', frac = '00'] = new Decimal(v).toFixed(2).split('.');
  const withSep = int.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return `${symbol}${withSep}.${frac}`;
};

/** Display symbol for a currency code. The two frontends each carry this map
 *  already; this is the copy the server uses, so a notification and the screen
 *  it refers to cannot disagree. */
export const CURRENCY_SYMBOLS: Record<string, string> = { HKD: 'HK$', SGD: 'S$' };

/** formatMoney with the symbol looked up from the currency code. */
export const formatCurrency = (v: MoneyInput, currency: string): string =>
  formatMoney(v, CURRENCY_SYMBOLS[currency] ?? '');
