import { formatUnits } from './format'

function toFiniteNumber(value: string | number | null | undefined): number | null {
  if (typeof value === 'number' && Number.isFinite(value)) return value
  if (typeof value === 'string' && value.trim() !== '') {
    const parsed = Number(value)
    if (Number.isFinite(parsed)) return parsed
  }
  return null
}

export function formatUsdValue(value: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: Math.abs(value) >= 100 ? 0 : 2,
  }).format(value)
}

export function getSecondaryDisplayValue(input: {
  rawAmount: string | number | null | undefined
  decimals?: number
  exchangeRate?: string | number | null
  displayCurrency: 'native' | 'usd'
}): string | null {
  if (input.displayCurrency !== 'usd') return null

  const exchangeRate = toFiniteNumber(input.exchangeRate)
  if (exchangeRate == null || exchangeRate < 0) return null

  const normalizedAmount = Number(formatUnits(input.rawAmount, input.decimals ?? 18, 8))
  if (!Number.isFinite(normalizedAmount)) return null

  return formatUsdValue(normalizedAmount * exchangeRate)
}
