import { NextResponse } from 'next/server'

export async function POST(request) {
  try {
    const { dexProvider, action, ...otherParams } = await request.json()
    
    console.log(`🔄 Unified trading request:`, { dexProvider, action, ...otherParams })

    if (!dexProvider) {
      return NextResponse.json({
        success: false,
        error: 'dexProvider is required (drift or jupiter)'
      }, { status: 400 })
    }

    // Route to the appropriate DEX provider
    let response
    
    if (dexProvider === 'drift') {
      // Import and call Drift functions directly
      try {
        const driftModule = await import('../../drift/trade/route.js')
        const mockRequest = {
          json: async () => ({ action, ...otherParams })
        }
        
        const driftResponse = await driftModule.POST(mockRequest)
        response = await driftResponse.json()
        
      } catch (driftError) {
        console.error('❌ Drift call failed:', driftError)
        response = {
          success: false,
          error: 'Drift trading failed',
          details: driftError.message
        }
      }
      
    } else if (dexProvider === 'jupiter') {
      // For Jupiter, we'll implement when needed
      response = {
        success: false,
        error: 'Jupiter integration pending',
        message: 'Jupiter DEX integration will be implemented next'
      }
      
    } else {
      return NextResponse.json({
        success: false,
        error: `Unsupported DEX provider: ${dexProvider}. Supported: drift, jupiter`
      }, { status: 400 })
    }

    // Add provider info to response
    return NextResponse.json({
      ...response,
      dexProvider,
      timestamp: Date.now()
    })

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

export async function GET() {
  return NextResponse.json({
    message: 'Unified Trading API',
    supportedProviders: ['drift', 'jupiter'],
    actions: {
      drift: ['get_balance', 'place_order', 'get_positions', 'close_position'],
      jupiter: ['swap', 'get_quote', 'get_routes']
    }
  })
}
