import { NextResponse } from 'next/server'
import priceMonitor from '../../../lib/price-monitor'

export async function GET() {
  try {
    // Get current monitoring data for all active trades
    const monitoringData = await priceMonitor.getTradeMonitoringData()
    const activeAlerts = priceMonitor.getActiveAlerts()
    
    // Get price cache for all common trading symbols + active trade symbols
    const baseSymbols = ['SOLUSD', 'BTCUSD', 'ETHUSD'] // Always show these
    const tradeSymbols = monitoringData.map(trade => trade.symbol)
    const allSymbols = [...new Set([...baseSymbols, ...tradeSymbols])]
    
    const priceData = {}
    for (const symbol of allSymbols) {
      const price = priceMonitor.getCurrentPrice(symbol)
      if (price) {
        priceData[symbol] = price
      } else {
        // Force fetch price if not cached
        const fetchedPrice = await priceMonitor.forceUpdatePrice(symbol)
        if (fetchedPrice) {
          priceData[symbol] = fetchedPrice
        }
      }
    }

    return NextResponse.json({
      success: true,
      data: {
        trades: monitoringData,
        alerts: activeAlerts,
        prices: priceData,
        lastUpdated: new Date().toISOString(),
        monitoringActive: priceMonitor.isMonitoring()
      }
    })
  } catch (error) {
    console.error('Error getting trade monitoring data:', error)
    return NextResponse.json({
      success: false,
      error: 'Failed to get monitoring data',
      details: error.message
    }, { status: 500 })
  }
}

export async function POST(request) {
  try {
    const { action, symbol } = await request.json()

    switch (action) {
      case 'force_update':
        if (symbol) {
          const price = await priceMonitor.forceUpdatePrice(symbol)
          return NextResponse.json({
            success: true,
            data: { symbol, price, updated: new Date().toISOString() }
          })
        }
        break

      case 'start_monitoring':
        await priceMonitor.startMonitoring()
        return NextResponse.json({
          success: true,
          message: 'Price monitoring started'
        })

      case 'stop_monitoring':
        await priceMonitor.stopMonitoring()
        return NextResponse.json({
          success: true,
          message: 'Price monitoring stopped'
        })

      default:
        return NextResponse.json({
          success: false,
          error: 'Invalid action'
        }, { status: 400 })
    }
  } catch (error) {
    console.error('Error in price monitoring action:', error)
    return NextResponse.json({
      success: false,
      error: 'Failed to execute action',
      details: error.message
    }, { status: 500 })
  }
}
