/**
 * Real Drift Protocol test with new minimum percentages
 * Tests with very small positions to validate order acceptance
 */

// Test the updated API endpoint with various percentages
async function testNewMinimums() {
  console.log('🧪 Testing New Minimum Percentages with Real API');
  console.log('   Updated minimums: 1.5% SL / 0.6% TP');
  console.log('   Testing with very small positions ($1-2)\n');

  const baseUrl = 'http://localhost:3000'; // Inside container, use internal port
  
  // Test cases focusing on scalping scenarios
  const testCases = [
    { sl: 0.5, tp: 0.3, size: 0.005, desc: 'Ultra-tight scalping' },
    { sl: 1.0, tp: 0.5, size: 0.005, desc: 'Tight scalping' },
    { sl: 1.5, tp: 0.6, size: 0.005, desc: 'At new minimums' },
    { sl: 2.0, tp: 1.0, size: 0.005, desc: 'Conservative scalping' }
  ];
  
  for (let i = 0; i < testCases.length; i++) {
    const testCase = testCases[i];
    console.log(`📋 Test ${i + 1}: ${testCase.desc}`);
    console.log(`   SL: ${testCase.sl}% / TP: ${testCase.tp}% / Size: $${(testCase.size * 200).toFixed(1)}`);
    
    try {
      // Test order placement via API
      const response = await fetch(`${baseUrl}/api/drift/trade`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          symbol: 'SOL-PERP',
          direction: 'LONG',
          size: testCase.size, // Very small position
          stopLossPercent: testCase.sl,
          takeProfitPercent: testCase.tp,
          test: true // Add test flag to avoid real trades
        })
      });
      
      const result = await response.json();
      
      if (response.ok) {
        console.log(`   ✅ SUCCESS: API accepted ${testCase.sl}%/${testCase.tp}% percentages`);
        
        if (result.minimumEnforced) {
          console.log(`   ⚠️  Minimums enforced:`);
          if (result.enforcedSL > testCase.sl) {
            console.log(`      SL: ${testCase.sl}% → ${result.enforcedSL}%`);
          }
          if (result.enforcedTP > testCase.tp) {
            console.log(`      TP: ${testCase.tp}% → ${result.enforcedTP}%`);
          }
        } else {
          console.log(`   🎯 Perfect: No enforcement needed`);
        }
        
      } else {
        console.log(`   ❌ FAILED: ${result.error || 'Unknown error'}`);
        
        // Check if it's a minimum percentage issue
        if (result.error && result.error.includes('minimum')) {
          console.log(`   📊 This indicates our new minimums are still too low`);
        }
      }
      
    } catch (error) {
      console.log(`   ❌ REQUEST FAILED: ${error.message}`);
    }
    
    console.log(''); // Empty line between tests
    
    // Wait between tests
    if (i < testCases.length - 1) {
      console.log('   ⏳ Waiting 3 seconds...\n');
      await new Promise(resolve => setTimeout(resolve, 3000));
    }
  }
}

// Test current balance to ensure we can make small trades
async function checkBalance() {
  console.log('💰 Checking Drift Account Balance...');
  
  try {
    const response = await fetch('http://localhost:3000/api/balance');
    const balance = await response.json();
    
    if (response.ok) {
      console.log(`   Total Collateral: $${balance.balance.toFixed(2)}`);
      console.log(`   Free Collateral: $${balance.collateral.toFixed(2)}`);
      
      if (balance.collateral < 10) {
        console.log('   ⚠️  Warning: Low collateral for testing');
        return false;
      }
      
      console.log('   ✅ Sufficient balance for small test trades\n');
      return true;
      
    } else {
      console.log(`   ❌ Failed to get balance: ${balance.error}`);
      return false;
    }
    
  } catch (error) {
    console.log(`   ❌ Balance check failed: ${error.message}`);
    return false;
  }
}

// Main test execution
async function main() {
  console.log('🚀 Testing Reduced Minimum Percentages with Real Drift API\n');
  
  // Check if container is accessible
  try {
    const response = await fetch('http://localhost:3000/api/status');
    const status = await response.json();
    console.log(`📡 API Status: ${status.status || 'Connected'}\n`);
  } catch (error) {
    console.log('❌ Cannot connect to API. Make sure container is running on port 9001');
    console.log('   Run: npm run docker:dev\n');
    return;
  }
  
  // Check balance first
  const hasBalance = await checkBalance();
  if (!hasBalance) {
    console.log('💡 Balance check failed, but continuing with validation tests...\n');
  }
  
  // Run the minimum percentage tests
  await testNewMinimums();
  
  // Summary and next steps
  console.log('📊 TEST SUMMARY');
  console.log('=' .repeat(50));
  console.log('✅ Completed testing new minimum percentages (1.5% SL / 0.6% TP)');
  console.log('📝 Review results above to confirm Drift Protocol acceptance');
  console.log('');
  console.log('🎯 NEXT STEPS:');
  console.log('1. If tests passed: try even lower minimums (1% SL / 0.5% TP)');
  console.log('2. If tests failed: increase minimums slightly');
  console.log('3. Test with real small trades once validation passes');
  console.log('4. Monitor execution success rates in live trading');
}

// Run the tests
main().catch(console.error);
