#!/usr/bin/env node

/**
 * Test HTTP Utility
 * 
 * Tests the HTTP utility for compatibility in environments with/without curl
 */

const HttpUtil = require('./lib/http-util');

async function testHttpUtil() {
  console.log('🔧 TESTING HTTP UTILITY');
  console.log('='.repeat(50));
  
  // Test curl availability
  const isCurlAvailable = await HttpUtil.checkCurlAvailability();
  console.log(`📋 curl available: ${isCurlAvailable ? '✅ YES' : '❌ NO'}`);
  
  if (isCurlAvailable) {
    console.log('   Will use curl for HTTP requests');
  } else {
    console.log('   Will use built-in Node.js http module');
  }
  
  console.log('\n🌐 Testing position monitor endpoint...');
  
  try {
    const data = await HttpUtil.get('http://localhost:9001/api/automation/position-monitor');
    
    console.log('✅ HTTP request successful!');
    console.log(`📊 Response: ${JSON.stringify(data, null, 2).substring(0, 200)}...`);
    
    if (data.success) {
      console.log('🎯 Position monitor API responding correctly');
      
      if (data.monitor?.hasPosition) {
        console.log(`📈 Active position: ${data.monitor.position?.symbol || 'Unknown'}`);
        console.log(`💰 P&L: $${data.monitor.position?.unrealizedPnl || 0}`);
        console.log(`⚠️ Distance to SL: ${data.monitor.stopLossProximity?.distancePercent || 'N/A'}%`);
      } else {
        console.log('📊 No active positions');
      }
    } else {
      console.log('⚠️ API responded but with success: false');
    }
    
  } catch (error) {
    console.log(`❌ HTTP request failed: ${error.message}`);
    
    if (error.message.includes('ECONNREFUSED')) {
      console.log('💡 Server not running on localhost:9001');
    } else if (error.message.includes('timeout')) {
      console.log('💡 Request timed out - server may be slow');
    } else {
      console.log('💡 Other error - check server status');
    }
  }
  
  console.log('\n🔧 HTTP Utility Test Complete');
  console.log(`✅ Fallback system ${isCurlAvailable ? 'not needed' : 'working'}`);
}

// Run the test
if (require.main === module) {
  testHttpUtil().catch(console.error);
}

module.exports = { testHttpUtil };
