#!/usr/bin/env node

/**
 * Debug API Response Test
 * Check exactly what the API returns for order placement
 */

async function debugAPIResponse() {
  console.log('🔍 DEBUG: Testing API Response for Order Placement')
  console.log('=' .repeat(60))
  
  try {
    const testOrder = {
      action: 'place_order',
      symbol: 'SOL',
      side: 'buy',
      amount: 0.5,
      leverage: 1,
      stopLoss: true,
      takeProfit: true,
      stopLossPercent: 0.5,
      takeProfitPercent: 0.25
    }
    
    console.log('📤 Sending request:')
    console.log(JSON.stringify(testOrder, null, 2))
    console.log('')
    
    const response = await fetch('http://localhost:3000/api/drift/trade', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(testOrder)
    })
    
    console.log('📥 Response status:', response.status)
    console.log('📥 Response headers:')
    for (const [key, value] of response.headers.entries()) {
      console.log(`  ${key}: ${value}`)
    }
    console.log('')
    
    const responseText = await response.text()
    console.log('📥 Raw response text:')
    console.log(responseText)
    console.log('')
    
    try {
      const result = JSON.parse(responseText)
      console.log('📊 Parsed response:')
      console.log(JSON.stringify(result, null, 2))
      
      // Specific checks
      console.log('')
      console.log('🔍 Response Analysis:')
      console.log('  Success:', result.success)
      console.log('  Has transactionId:', !!result.transactionId)
      console.log('  TransactionId value:', result.transactionId)
      console.log('  Has symbol:', !!result.symbol)
      console.log('  Symbol value:', result.symbol)
      console.log('  Has amount:', !!result.amount)
      console.log('  Amount value:', result.amount)
      console.log('  Has error:', !!result.error)
      console.log('  Error value:', result.error)
      
    } catch (parseError) {
      console.log('❌ Failed to parse response as JSON:', parseError.message)
    }
    
  } catch (error) {
    console.error('❌ Test failed:', error.message)
  }
}

if (require.main === module) {
  debugAPIResponse()
}

module.exports = { debugAPIResponse }
