import { NextResponse } from 'next/server'

export async function POST(request) {
  try {
    console.log('🔄 Unified trading endpoint called...')

    const { 
      dexProvider, 
      action, 
      symbol, 
      amount, 
      side, 
      leverage = 1,
      stopLoss,
      takeProfit,
      stopLossPercent,
      takeProfitPercent,
      mode = 'SIMULATION'
    } = await request.json()

    // Validate required parameters
    if (!dexProvider) {
      return NextResponse.json({
        success: false,
        error: 'DEX provider not specified'
      }, { status: 400 })
    }

    console.log(`📊 Trading request:`, {
      dexProvider,
      action,
      symbol,
      amount,
      side,
      leverage,
      stopLoss,
      takeProfit,
      stopLossPercent,
      takeProfitPercent,
      mode
    })

    // For simulation mode, return mock data
    if (mode === 'SIMULATION') {
      console.log('🎭 Simulation mode - returning mock response')
      return NextResponse.json({
        success: true,
        simulation: true,
        dexProvider,
        action,
        result: {
          transactionId: `sim_${Date.now()}`,
          symbol,
          side,
          amount,
          leverage,
          mode: 'SIMULATION',
          message: 'Simulated trade executed successfully'
        }
      })
    }

    // Route to appropriate DEX based on provider
    let response
    
    if (dexProvider === 'DRIFT') {
      console.log('🌊 Routing to Drift Protocol...')
      
      // Call Drift API with correct action for trading
      const driftResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/drift/trade`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          action: 'place_order',
          symbol: symbol.replace('USD', ''), // Convert SOLUSD to SOL
          amount,
          side,
          leverage,
          // Pass through stop loss and take profit parameters
          stopLoss: stopLoss !== undefined ? stopLoss : true,
          takeProfit: takeProfit !== undefined ? takeProfit : true,
          riskPercent: stopLossPercent || 2, // Use actual stop loss percentage from config
          takeProfitPercent: takeProfitPercent || 4 // Use actual take profit percentage from config
        })
      })

      response = await driftResponse.json()
      
      if (response.success) {
        response.dexProvider = 'DRIFT'
        response.leverageUsed = leverage
      }

    } else if (dexProvider === 'JUPITER') {
      console.log('🪐 Routing to Jupiter DEX...')
      
      // Call Jupiter API (you may need to implement this endpoint)
      const jupiterResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/jupiter/trade`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          action,
          symbol,
          amount,
          side
        })
      })

      if (jupiterResponse.ok) {
        response = await jupiterResponse.json()
        response.dexProvider = 'JUPITER'
        response.leverageUsed = 1 // Jupiter is spot only
      } else {
        response = {
          success: false,
          error: 'Jupiter DEX integration not yet implemented',
          dexProvider: 'JUPITER'
        }
      }

    } else {
      return NextResponse.json({
        success: false,
        error: `Unsupported DEX provider: ${dexProvider}`
      }, { status: 400 })
    }

    console.log('✅ DEX response received:', response.success ? 'SUCCESS' : 'FAILED')

    return NextResponse.json(response)

  } catch (error) {
    console.error('❌ Unified trading error:', error)
    
    return NextResponse.json({
      success: false,
      error: 'Trading execution failed',
      details: error.message
    }, { status: 500 })
  }
}
