import {
  evaluateDecimalExpression,
  isFiniteNumber,
  roundTo,
  toFiniteNumberOrNull
} from '@/lib/decimal'

export { isFiniteNumber, toFiniteNumberOrNull }

export const parseNumberOrNull = (
  value: unknown,
  options?: { sanitize?: boolean; precision?: number }
): number | null => {
  if (value === '' || value == null) return null

  const normalizedValue =
    options?.sanitize && typeof value === 'string'
      ? value.replace(/[^0-9.+\-*/()\s]/g, '')
      : value

  if (normalizedValue === '' || normalizedValue == null) return null

  const normalized =
    typeof normalizedValue === 'string' ? normalizedValue.trim() : normalizedValue
  if (normalized === '') return null

  let numericValue = Number(normalized)
  if (!Number.isFinite(numericValue) && typeof normalized === 'string') {
    const evaluated = evaluateDecimalExpression(normalized)
    if (evaluated == null || !Number.isFinite(evaluated)) return null
    numericValue = evaluated
  }
  if (!Number.isFinite(numericValue)) return null

  const precision = options?.precision
  if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 0) {
    return numericValue
  }

  return roundTo(numericValue, precision)
}
