import { parseNumberOrNull } from '@/lib/number'

const fixedFormatterCache = new Map<number, Intl.NumberFormat>()
const flexibleFormatterCache = new Map<number, Intl.NumberFormat>()

const getFixedFormatter = (fractionDigits: number) => {
  if (!fixedFormatterCache.has(fractionDigits)) {
    fixedFormatterCache.set(
      fractionDigits,
      new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: fractionDigits,
        maximumFractionDigits: fractionDigits
      })
    )
  }
  return fixedFormatterCache.get(fractionDigits)!
}

const getFlexibleFormatter = (maxFractionDigits: number) => {
  if (!flexibleFormatterCache.has(maxFractionDigits)) {
    flexibleFormatterCache.set(
      maxFractionDigits,
      new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 0,
        maximumFractionDigits: maxFractionDigits
      })
    )
  }
  return flexibleFormatterCache.get(maxFractionDigits)!
}

export const formatThousands = (value: unknown, fractionDigits = 2) => {
  const numericValue = parseNumberOrNull(value)
  if (numericValue == null) return ''
  return getFixedFormatter(fractionDigits).format(numericValue)
}

export const formatThousandsFlexible = (value: unknown, maxFractionDigits = 20) => {
  const numericValue = parseNumberOrNull(value)
  if (numericValue == null) return ''
  return getFlexibleFormatter(maxFractionDigits).format(numericValue)
}
