// Direct API test to place REAL orders via the trading endpoint
const https = require('https');
const http = require('http');

async function testRealOrderViaAPI() {
  console.log('🚀 REAL DRIFT ORDER TEST VIA API');
  console.log('============================================================');
  console.log('⚠️  This will place a REAL $1 order using the trading API');
  console.log('📋 Order should appear in Drift Protocol interface');
  console.log('============================================================\n');

  // Test different percentage levels
  const testCases = [
    { 
      stopLossPercent: 1.5, 
      takeProfitPercent: 1.0, 
      name: 'Conservative Scalping (1.5%/1.0%)'
    },
    { 
      stopLossPercent: 1.0, 
      takeProfitPercent: 0.75, 
      name: 'Moderate Scalping (1.0%/0.75%)'
    },
    { 
      stopLossPercent: 0.5, 
      takeProfitPercent: 0.25, 
      name: 'Tight Scalping (0.5%/0.25%)'
    },
    { 
      stopLossPercent: 0.25, 
      takeProfitPercent: 0.1, 
      name: 'Ultra-tight Scalping (0.25%/0.1%)'
    }
  ];

  const successfulTests = [];

  for (const testCase of testCases) {
    console.log(`🔬 Testing: ${testCase.name}`);
    console.log(`   Stop Loss: ${testCase.stopLossPercent}%`);
    console.log(`   Take Profit: ${testCase.takeProfitPercent}%`);

    try {
      const orderData = {
        symbol: 'SOL-PERP',
        side: 'buy',
        amount: 1, // $1 USD
        orderType: 'market',
        stopLoss: true,
        takeProfit: true,
        stopLossPercent: testCase.stopLossPercent,
        takeProfitPercent: testCase.takeProfitPercent,
        leverage: 1
      };

      console.log(`   📤 Placing real order...`);

      const response = await makeAPIRequest('POST', '/api/drift/trade', orderData);
      
      if (response.success) {
        console.log(`   ✅ SUCCESS: Order placed successfully!`);
        console.log(`   📋 Response:`, JSON.stringify(response, null, 2));
        
        successfulTests.push({
          ...testCase,
          response: response
        });

        // Wait 5 seconds before closing the position
        console.log(`   ⏳ Waiting 5 seconds before closing position...`);
        await new Promise(resolve => setTimeout(resolve, 5000));

        // Close the position
        const closeData = {
          symbol: 'SOL-PERP',
          side: 'sell',
          amount: 1,
          orderType: 'market'
        };

        const closeResponse = await makeAPIRequest('POST', '/api/drift/trade', closeData);
        
        if (closeResponse.success) {
          console.log(`   🧹 Position closed successfully`);
        } else {
          console.log(`   ⚠️  Warning: Could not close position automatically`);
          console.log(`   📋 Close response:`, JSON.stringify(closeResponse, null, 2));
        }

      } else {
        console.log(`   ❌ FAILED: ${response.error || 'Unknown error'}`);
        console.log(`   📋 Full response:`, JSON.stringify(response, null, 2));
      }

    } catch (error) {
      console.log(`   ❌ FAILED: ${error.message}`);
    }

    console.log(''); // Empty line for readability
    
    // Wait between tests to avoid rate limiting
    await new Promise(resolve => setTimeout(resolve, 3000));
  }

  // Summary
  console.log('🎯 FINAL RESULTS:');
  console.log('============================================================');
  
  if (successfulTests.length > 0) {
    console.log(`✅ Successfully placed ${successfulTests.length}/${testCases.length} orders`);
    
    const tightestTest = successfulTests.reduce((tightest, current) => {
      return current.stopLossPercent < tightest.stopLossPercent ? current : tightest;
    });

    console.log(`\n🏆 TIGHTEST SUCCESSFUL PERCENTAGES:`);
    console.log(`   Stop Loss: ${tightestTest.stopLossPercent}%`);
    console.log(`   Take Profit: ${tightestTest.takeProfitPercent}%`);
    console.log(`   Test: ${tightestTest.name}`);

    console.log(`\n💡 RECOMMENDED API UPDATE:`);
    console.log(`   stopLossPercentCalc = Math.max(stopLossPercent / 100, ${(tightestTest.stopLossPercent / 100).toFixed(4)}) // ${tightestTest.stopLossPercent}%`);
    console.log(`   takeProfitPercentCalc = Math.max(takeProfitPercent / 100, ${(tightestTest.takeProfitPercent / 100).toFixed(4)}) // ${tightestTest.takeProfitPercent}%`);

  } else {
    console.log('❌ No orders were successfully placed');
    console.log('   Current minimum percentages appear to be necessary');
  }
}

function makeAPIRequest(method, path, data) {
  return new Promise((resolve, reject) => {
    const postData = JSON.stringify(data);
    
    const options = {
      hostname: 'localhost',
      port: 3000,
      path: path,
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    const req = http.request(options, (res) => {
      let responseData = '';

      res.on('data', (chunk) => {
        responseData += chunk;
      });

      res.on('end', () => {
        try {
          const parsedData = JSON.parse(responseData);
          resolve(parsedData);
        } catch (e) {
          resolve({ success: false, error: 'Invalid JSON response', raw: responseData });
        }
      });
    });

    req.on('error', (error) => {
      reject(error);
    });

    req.write(postData);
    req.end();
  });
}

// Safety check
if (process.argv.includes('--confirm')) {
  testRealOrderViaAPI().catch(console.error);
} else {
  console.log('⚠️  SAFETY CONFIRMATION REQUIRED ⚠️');
  console.log('This test will place REAL $1 orders on Drift Protocol');
  console.log('Orders will be automatically closed after testing');
  console.log('');
  console.log('To proceed, run: node test-api-real-orders.js --confirm');
}
