import { fix } from './fix'
import { removeTrailingZeros } from './removeTrailingZeros'
import type { BigDecimal } from './type'

export const divide = (
  x: BigDecimal,
  y: BigDecimal,
  fixDecimals?: number,
  rounding: 'round' | 'floor' | 'ceil' = 'round',
): BigDecimal => {
  // adjust the decimals and divide the values.
  const fixDecimalsX =
    fixDecimals === undefined || fixDecimals < x.decimals
      ? x.decimals
      : fixDecimals + 1
  const fixValueX =
    fixDecimals === undefined || fixDecimals < x.decimals
      ? x.value
      : x.value * 10n ** BigInt(fixDecimals + 1 - x.decimals)
  const valueX = fixValueX * 10n ** BigInt(y.decimals)
  const valueY = y.value
  const value = valueX / valueY

  if (fixDecimals === undefined) {
    // remove trailing zeros.
    return removeTrailingZeros({ value, decimals: fixDecimalsX })
  }

  return fix({ value, decimals: fixDecimalsX }, fixDecimals, rounding)
}
