import { Decimal } from '@rms/domain';

/**
 * A sum written out, as a receipt says it under the figures: "HONG KONG
 * DOLLARS ONE THOUSAND TWO HUNDRED AND FIFTY AND CENTS FIFTY ONLY". British
 * usage — "and" after the hundreds, and before a last group under a hundred —
 * in capitals without hyphens, the way the office's ERP receipts print it.
 */

const ONES = [
  '', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN',
  'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN',
];
const TENS = ['', '', 'TWENTY', 'THIRTY', 'FORTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'];
const SCALES = ['', 'THOUSAND', 'MILLION', 'BILLION', 'TRILLION'];

/** What each currency is called in words. One the list does not know is
 *  written by its code, which still reads. */
const CURRENCY_WORDS: Record<string, string> = {
  HKD: 'HONG KONG DOLLARS',
  SGD: 'SINGAPORE DOLLARS',
};

function belowHundred(n: number): string {
  if (n < 20) return ONES[n];
  return [TENS[Math.floor(n / 10)], ONES[n % 10]].filter(Boolean).join(' ');
}

function belowThousand(n: number): string {
  const hundreds = Math.floor(n / 100);
  const rest = n % 100;
  const head = hundreds ? `${ONES[hundreds]} HUNDRED` : '';
  if (!rest) return head;
  return head ? `${head} AND ${belowHundred(rest)}` : belowHundred(rest);
}

/** A whole number in words; "ZERO" for none. */
export function integerInWords(n: number): string {
  if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`Cannot write ${n} in words`);
  if (n === 0) return 'ZERO';
  const groups: number[] = [];
  for (let rest = n; rest > 0; rest = Math.floor(rest / 1000)) groups.push(rest % 1000);
  const words: string[] = [];
  for (let i = groups.length - 1; i >= 0; i--) {
    if (!groups[i]) continue;
    // "ONE THOUSAND AND FIVE": a last group with no hundreds is joined by "and".
    const joined = i === 0 && groups.length > 1 && groups[0] < 100 ? 'AND ' : '';
    words.push(`${joined}${belowThousand(groups[i])}${SCALES[i] ? ` ${SCALES[i]}` : ''}`);
  }
  return words.join(' ');
}

/** "HONG KONG DOLLARS … [AND CENTS …] ONLY". */
export function amountInWords(amount: string | number, currency: string): string {
  const [whole, cents] = new Decimal(String(amount)).abs().toFixed(2).split('.').map(Number);
  const name = CURRENCY_WORDS[currency] ?? currency;
  return `${name} ${integerInWords(whole)}${cents ? ` AND CENTS ${belowHundred(cents)}` : ''} ONLY`;
}
