/**
 * Currency formatting utilities
 *
 * These utilities handle formatting of USD currency values for display.
 * Database stores values as NUMERIC (exact decimal precision), JavaScript
 * uses number (IEEE 754 floating point).
 */

/**
 * Format USD amount for display
 *
 * @param amountUsd - Amount in USD (e.g., 1.375 = $1.38)
 * @param options - Formatting options
 * @returns Formatted string (e.g., "$1.38")
 *
 * @example
 * formatCurrency(1.375) // "$1.38"
 * formatCurrency(0.001) // "$0.00"
 * formatCurrency(1234.56) // "$1,234.56"
 * formatCurrency(1.5, { minimumFractionDigits: 4 }) // "$1.5000"
 */
export function formatCurrency(
  amountUsd: number,
  options: {
    minimumFractionDigits?: number
    maximumFractionDigits?: number
  } = {}
): string {
  const {
    minimumFractionDigits = 2,
    maximumFractionDigits = 2
  } = options

  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits,
    maximumFractionDigits
  }).format(amountUsd)
}

/**
 * Format USD amount with high precision (for debugging/technical displays)
 *
 * @param amountUsd - Amount in USD
 * @returns Formatted string with 6 decimal places (e.g., "$0.001375")
 *
 * @example
 * formatCurrencyPrecise(0.001375) // "$0.001375"
 * formatCurrencyPrecise(1.5) // "$1.500000"
 */
export function formatCurrencyPrecise(amountUsd: number): string {
  return formatCurrency(amountUsd, {
    minimumFractionDigits: 6,
    maximumFractionDigits: 6
  })
}

/**
 * Format USD amount as compact notation (for charts/dashboards)
 *
 * @param amountUsd - Amount in USD
 * @returns Compact formatted string (e.g., "$1.2K", "$3.5M")
 *
 * @example
 * formatCurrencyCompact(1234) // "$1.2K"
 * formatCurrencyCompact(1500000) // "$1.5M"
 * formatCurrencyCompact(5) // "$5"
 */
export function formatCurrencyCompact(amountUsd: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    notation: 'compact',
    minimumFractionDigits: 0,
    maximumFractionDigits: 1
  }).format(amountUsd)
}

/**
 * Parse string USD amount to number (for form inputs)
 *
 * @param value - String value (e.g., "$1,234.56" or "1234.56")
 * @returns Parsed number or null if invalid
 *
 * @example
 * parseCurrency("$1,234.56") // 1234.56
 * parseCurrency("1234.56") // 1234.56
 * parseCurrency("invalid") // null
 */
export function parseCurrency(value: string): number | null {
  // Remove currency symbol and commas
  const cleaned = value.replace(/[$,]/g, '').trim()
  const parsed = parseFloat(cleaned)
  return isNaN(parsed) ? null : parsed
}
