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

export const fix = (
  { value, decimals }: BigDecimal,
  fixDecimals: number,
  rounding: 'round' | 'floor' | 'ceil',
): BigDecimal => {
  if (decimals <= fixDecimals) {
    return removeTrailingZeros({ value, decimals })
  }

  const fixPlusOneValue = value / 10n ** BigInt(decimals - fixDecimals - 1)
  const fixValue = round(fixPlusOneValue, rounding)

  return removeTrailingZeros({
    value: fixValue,
    decimals: fixDecimals,
  })
}

const round = (value: bigint, rounding: 'round' | 'floor' | 'ceil'): bigint => {
  switch (rounding) {
    case 'ceil': {
      if (value < 0n) {
        return (value - 9n) / 10n
      }
      return (value + 9n) / 10n
    }
    case 'floor': {
      return value / 10n
    }
    case 'round': {
      if (value < 0n) {
        return (value - 5n) / 10n
      }
      return (value + 5n) / 10n
    }
  }
}
