import { safeHandler } from '@/lib/auth'
import { NextRequest, NextResponse } from 'next/server'
import { getExchangeRates } from '@/lib/currency'

export const GET = safeHandler(async (req: NextRequest) => {
  const { searchParams } = new URL(req.url)
  const from = (searchParams.get('from') || 'USD').toUpperCase()
  const to = (searchParams.get('to') || 'INR').toUpperCase()
  const amount = parseFloat(searchParams.get('amount') || '0')

  if (amount <= 0) {
    return NextResponse.json(
      { message: 'Amount must be greater than 0' },
      { status: 400 }
    )
  }

  const rates = await getExchangeRates(from)
  const rate = rates[to]

  if (rate === undefined) {
    return NextResponse.json(
      { message: `No exchange rate found for ${from} -> ${to}` },
      { status: 400 }
    )
  }

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

  return NextResponse.json({
    from,
    to,
    amount,
    convertedAmount,
    rate,
  })
})
