// Exchange rate fetcher with 1-hour in-memory cache
// Uses https://open.er-api.com/v6/latest/{base} (free, no API key needed)

interface CacheEntry {
  rates: Record<string, number>
  timestamp: number
}

const CACHE_TTL = 60 * 60 * 1000 // 1 hour in milliseconds
const cache = new Map<string, CacheEntry>()

export async function getExchangeRates(base: string): Promise<Record<string, number>> {
  const upperBase = base.toUpperCase()
  const cached = cache.get(upperBase)

  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.rates
  }

  const response = await fetch(`https://open.er-api.com/v6/latest/${upperBase}`)

  if (!response.ok) {
    throw new Error(`Failed to fetch exchange rates for ${upperBase}`)
  }

  const data = await response.json()

  if (data.result !== 'success') {
    throw new Error(`Exchange rate API error: ${data['error-type'] || 'unknown'}`)
  }

  const rates: Record<string, number> = data.rates

  cache.set(upperBase, {
    rates,
    timestamp: Date.now(),
  })

  return rates
}

export async function convertCurrency(
  amount: number,
  from: string,
  to: string
): Promise<{ convertedAmount: number; rate: number }> {
  const upperFrom = from.toUpperCase()
  const upperTo = to.toUpperCase()

  if (upperFrom === upperTo) {
    return { convertedAmount: amount, rate: 1 }
  }

  const rates = await getExchangeRates(upperFrom)
  const rate = rates[upperTo]

  if (rate === undefined) {
    throw new Error(`No exchange rate found for ${upperFrom} -> ${upperTo}`)
  }

  const convertedAmount = Math.round(amount * rate * 100) / 100

  return { convertedAmount, rate }
}
