import { ApiClient } from './base'

export interface Currency {
  code: string
  fractionalDigits: number
  numericCode: number
  symbol: string
}

export class DataApiClient extends ApiClient {
  getCurrencies(): Promise<Currency[]> {
    return super.getJson('/currencies')
  }
}

/**
 * Formats a money value (integer amount and currency) as a string.
 * @param amount The integer amount to format.
 * @param currency The currency of the value.
 * @returns A string representation of the money value.
 */
export function formatMoney(amount: number, currency: Currency) {
  const format = new Intl.NumberFormat(undefined, {
    currency: currency.code,
    style: 'currency',
    currencyDisplay: 'narrowSymbol',
  })
  return format.format(amount / Math.pow(10, currency.fractionalDigits))
}

export function floatMoneyToInteger(amount: number, currency: Currency) {
  return Math.round(amount * Math.pow(10, currency.fractionalDigits ?? 0))
}

export function integerMoneyToFloat(amount: number, currency: Currency) {
  return amount / Math.pow(10, currency.fractionalDigits ?? 0)
}
