import { NextResponse } from 'next/server'

export async function GET(request) {
  const { searchParams } = new URL(request.url)
  const symbol = searchParams.get('symbol') || 'BTCUSD'
  
  try {
    // Map symbols to CoinGecko IDs
    const symbolMap = {
      'BTCUSD': 'bitcoin',
      'ETHUSD': 'ethereum',
      'SOLUSD': 'solana',
      'SUIUSD': 'sui',
      'ADAUSD': 'cardano',
      'DOGEUSD': 'dogecoin',
      'XRPUSD': 'ripple',
      'AVAXUSD': 'avalanche-2',
      'LINKUSD': 'chainlink',
      'MATICUSD': 'matic-network'
    }

    const coinId = symbolMap[symbol.toUpperCase()] || 'bitcoin'
    
    // Fetch from CoinGecko API
    const response = await fetch(
      `https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd`,
      {
        headers: {
          'Accept': 'application/json',
        }
      }
    )

    if (!response.ok) {
      throw new Error(`CoinGecko API error: ${response.status}`)
    }

    const data = await response.json()
    const price = data[coinId]?.usd

    if (!price) {
      throw new Error('Price not found')
    }

    return NextResponse.json({
      symbol: symbol.toUpperCase(),
      price: price,
      source: 'coingecko'
    })

  } catch (error) {
    console.error('Price fetch error:', error)
    
    // Return fallback prices for testing
    const fallbackPrices = {
      'BTCUSD': 100000,
      'ETHUSD': 4000,
      'SOLUSD': 200,
      'SUIUSD': 4.5,
      'ADAUSD': 1.2,
      'DOGEUSD': 0.4,
      'XRPUSD': 2.5,
      'AVAXUSD': 45,
      'LINKUSD': 20,
      'MATICUSD': 1.1
    }

    return NextResponse.json({
      symbol: symbol.toUpperCase(),
      price: fallbackPrices[symbol.toUpperCase()] || 100,
      source: 'fallback',
      error: error.message
    })
  }
}
