import { NextResponse } from 'next/server'

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { 
      symbol, 
      side, 
      amount, 
      type = 'market', 
      price, 
      stopLoss, 
      takeProfit,
      tradingMode = 'SPOT',
      fromCoin,
      toCoin,
      limitOrderId 
    } = body

    // Validate input
    if (!symbol || !side || !amount) {
      return NextResponse.json({
        error: 'Missing required fields: symbol, side, amount'
      }, { status: 400 })
    }

    // Validate balance before proceeding (skip for limit order fills)
    if (!limitOrderId) {
      console.log('🔍 Validating wallet balance before trade execution...')
      
      try {
        const validationResponse = await fetch('http://localhost:3000/api/trading/validate', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            symbol,
            side,
            amount,
            price,
            tradingMode,
            fromCoin,
            toCoin
          })
        })

        const validationResult = await validationResponse.json()
        
        if (!validationResult.success) {
          console.log('❌ Balance validation failed:', validationResult.message)
          return NextResponse.json({
            success: false,
            error: validationResult.error,
            message: validationResult.message,
            validation: validationResult
          }, { status: validationResponse.status })
        }
        
        console.log('✅ Balance validation passed')
      } catch (validationError) {
        console.error('❌ Balance validation error:', validationError)
        return NextResponse.json({
          success: false,
          error: 'VALIDATION_FAILED',
          message: 'Could not validate wallet balance. Please try again.'
        }, { status: 500 })
      }
    }

    // Handle limit orders
    if (type === 'limit' && price && !limitOrderId) {
      console.log(`📋 Creating limit order: ${side.toUpperCase()} ${amount} ${symbol} at $${price}`)
      
      // Create pending order instead of executing immediately
      try {
        const orderResponse = await fetch('http://localhost:3000/api/trading/orders', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            action: 'add',
            symbol: symbol,
            side: side.toUpperCase(),
            amount: amount,
            limitPrice: price,
            stopLoss: stopLoss,
            takeProfit: takeProfit,
            tradingMode: tradingMode,
            fromCoin: fromCoin,
            toCoin: toCoin
          })
        })

        if (orderResponse.ok) {
          const orderData = await orderResponse.json()
          return NextResponse.json({
            success: true,
            order: orderData.order,
            type: 'limit_order_created',
            message: `Limit order created: ${side.toUpperCase()} ${amount} ${symbol} at $${price}`
          })
        } else {
          throw new Error('Failed to create limit order')
        }
      } catch (error) {
        console.error('Failed to create limit order:', error)
        return NextResponse.json({
          error: 'Failed to create limit order',
          message: error instanceof Error ? error.message : 'Unknown error'
        }, { status: 500 })
      }
    }

    // Get current market price for market orders or limit order fills
    const currentPrice = type === 'market' ? (side === 'buy' ? 168.11 : 168.09) : price

    // Mock trading execution (market order or limit order fill)
    const mockTrade = {
      id: limitOrderId ? `fill_${limitOrderId}` : `trade_${Date.now()}`,
      symbol,
      side, // 'buy' or 'sell'
      amount: parseFloat(amount),
      type,
      price: currentPrice,
      status: 'executed',
      timestamp: new Date().toISOString(),
      fee: parseFloat(amount) * 0.001, // 0.1% fee
      limitOrderId: limitOrderId || null
    }

    console.log('Trade executed:', mockTrade)

    // Automatically create position for this trade
    try {
      const positionResponse = await fetch('http://localhost:3000/api/trading/positions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'add',
          symbol: fromCoin && toCoin ? `${fromCoin}/${toCoin}` : mockTrade.symbol,
          side: mockTrade.side.toUpperCase(),
          amount: mockTrade.amount,
          entryPrice: mockTrade.price,
          stopLoss: stopLoss,
          takeProfit: takeProfit,
          txId: mockTrade.id,
          leverage: tradingMode === 'PERP' ? 10 : 1
        })
      })
      
      if (positionResponse.ok) {
        const positionData = await positionResponse.json()
        console.log('Position created:', positionData.position?.id)
      }
    } catch (error) {
      console.error('Failed to create position:', error)
    }

    return NextResponse.json({
      success: true,
      trade: mockTrade,
      message: `Successfully ${side} ${amount} ${symbol}`
    })
  } catch (error) {
    return NextResponse.json({
      error: 'Failed to execute trade',
      message: error instanceof Error ? error.message : 'Unknown error'
    }, { status: 500 })
  }
}

export async function GET() {
  return NextResponse.json({
    message: 'Trading endpoint is active. Use POST to execute trades.',
    supportedMethods: ['POST'],
    requiredFields: ['symbol', 'side', 'amount'],
    optionalFields: ['type'],
    positions: [
      { symbol: 'SOL', size: 1.5, entryPrice: 140.50, markPrice: 144.11, unrealizedPnl: 5.415 },
      { symbol: 'ETH', size: 0.1, entryPrice: 2350, markPrice: 2400, unrealizedPnl: 5.0 }
    ]
  })
}
