/** Minor-unit money, per docs/backend/PHASE-1-MONEY-FX-PAYMENTS-CONTRACT.md §2. No float for money math. */
export interface Money {
  amountMinor: number;
  currency: string;
}

const MINOR_UNIT_DECIMALS: Record<string, number> = {
  RUB: 2,
  USD: 2,
  EUR: 2,
  AMD: 2,
};

export function decimalsFor(currency: string): number {
  return MINOR_UNIT_DECIMALS[currency] ?? 2;
}

export function toMajor(money: Money): number {
  return money.amountMinor / Math.pow(10, decimalsFor(money.currency));
}

export function fromMajor(amount: number, currency: string): Money {
  const decimals = decimalsFor(currency);
  return { amountMinor: Math.round(amount * Math.pow(10, decimals)), currency };
}

export function addMoney(a: Money, b: Money): Money {
  if (a.currency !== b.currency) {
    throw new Error(`Cannot add Money of different currencies: ${a.currency} vs ${b.currency}`);
  }
  return { amountMinor: a.amountMinor + b.amountMinor, currency: a.currency };
}

export function subtractMoney(a: Money, b: Money): Money {
  if (a.currency !== b.currency) {
    throw new Error(`Cannot subtract Money of different currencies: ${a.currency} vs ${b.currency}`);
  }
  return { amountMinor: a.amountMinor - b.amountMinor, currency: a.currency };
}

export function multiplyMoney(money: Money, factor: number): Money {
  return { amountMinor: Math.round(money.amountMinor * factor), currency: money.currency };
}

export function zeroMoney(currency: string): Money {
  return { amountMinor: 0, currency };
}
