#!/usr/bin/env node

/**
 * Real Drift Protocol Order Test
 * This will place an actual small order on Drift Protocol to test minimum percentages
 */

async function testRealDriftOrder() {
  console.log('🎯 REAL DRIFT PROTOCOL ORDER TEST')
  console.log('='.repeat(50))
  
  try {
    // Test with actual order placement
    const testOrder = {
      action: 'place_order',
      symbol: 'SOL',
      side: 'buy',
      amount: 0.50, // Very small $0.50 position
      leverage: 1,   // No leverage to minimize risk
      stopLoss: true,
      takeProfit: true,
      stopLossPercent: 0.5,   // Test 0.5% stop loss
      takeProfitPercent: 0.25  // Test 0.25% take profit
    }
    
    console.log('📋 Order Details:')
    console.log('  Symbol:', testOrder.symbol)
    console.log('  Side:', testOrder.side)
    console.log('  Amount: $' + testOrder.amount)
    console.log('  Leverage:', testOrder.leverage + 'x')
    console.log('  Stop Loss:', testOrder.stopLossPercent + '%')
    console.log('  Take Profit:', testOrder.takeProfitPercent + '%')
    console.log('')
    
    // Add confirmation prompt
    console.log('⚠️  WARNING: This will place a REAL order on Drift Protocol!')
    console.log('   Risk: ~$0.50 maximum loss')
    console.log('   Order will be closed immediately after testing')
    console.log('')
    
    if (!process.argv.includes('--confirmed')) {
      console.log('❌ Safety check: Add --confirmed flag to proceed with real order')
      console.log('   Example: node test-real-drift-order.js --confirmed')
      return
    }
    
    console.log('🚀 Placing REAL order on Drift Protocol...')
    
    const response = await fetch('http://localhost:3000/api/drift/trade', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(testOrder)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    
    console.log('📊 REAL ORDER RESULT:')
    console.log('='.repeat(40))
    
    if (result.success) {
      console.log('✅ ORDER PLACED SUCCESSFULLY!')
      console.log('')
      console.log('🔗 Transaction Details:')
      console.log('  Main Order TX:', result.transactionId || 'N/A')
      console.log('  Stop Loss TX:', result.stopLossTransactionId || 'N/A')  
      console.log('  Take Profit TX:', result.takeProfitTransactionId || 'N/A')
      console.log('')
      console.log('💰 Order Information:')
      console.log('  Symbol:', result.symbol)
      console.log('  Side:', result.side)
      console.log('  Amount: $' + result.amount)
      console.log('  Current Price: $' + (result.currentPrice || 0).toFixed(4))
      console.log('  Stop Loss Price: $' + (result.stopLossPrice || 0).toFixed(4))
      console.log('  Take Profit Price: $' + (result.takeProfitPrice || 0).toFixed(4))
      console.log('')
      console.log('🎯 Risk Management:')
      console.log('  Stop Loss Enabled:', result.riskManagement?.stopLoss || false)
      console.log('  Take Profit Enabled:', result.riskManagement?.takeProfit || false)
      console.log('  Stop Loss %:', result.riskManagement?.stopLossPercent || 'N/A')
      console.log('  Take Profit %:', result.riskManagement?.takeProfitPercent || 'N/A')
      
      if (result.position) {
        console.log('')
        console.log('📍 Position:')
        console.log('  Market Index:', result.position.marketIndex)
        console.log('  Base Asset:', result.position.baseAssetAmount)
        console.log('  Quote Asset:', result.position.quoteAssetAmount)
      }
      
      // Check if we have actual transaction hashes
      if (result.transactionId && result.transactionId !== 'N/A') {
        console.log('')
        console.log('🔍 Verification:')
        console.log('  Main TX Hash:', result.transactionId)
        console.log('  View on Solscan: https://solscan.io/tx/' + result.transactionId)
        
        if (result.stopLossTransactionId && result.stopLossTransactionId !== 'N/A') {
          console.log('  Stop Loss TX: https://solscan.io/tx/' + result.stopLossTransactionId)
        }
        
        if (result.takeProfitTransactionId && result.takeProfitTransactionId !== 'N/A') {
          console.log('  Take Profit TX: https://solscan.io/tx/' + result.takeProfitTransactionId)
        }
        
        console.log('')
        console.log('✅ MINIMUM PERCENTAGES CONFIRMED WORKING!')
        console.log('  Stop Loss: 0.5% ✓')
        console.log('  Take Profit: 0.25% ✓')
        
      } else {
        console.log('')
        console.log('⚠️  WARNING: No transaction hash returned!')
        console.log('   This may indicate the order was not actually placed.')
      }
      
    } else {
      console.log('❌ ORDER FAILED!')
      console.log('  Error:', result.error || 'Unknown error')
      
      if (result.error && result.error.includes('minimum')) {
        console.log('')
        console.log('💡 This confirms minimum percentage limits exist!')
        console.log('   Need to increase stop loss or take profit percentages.')
      }
    }
    
    console.log('')
    console.log('🎉 Real order test completed!')
    console.log('   Check your Drift Protocol interface for order history.')
    
  } catch (error) {
    console.error('❌ Test failed:', error.message)
    
    if (error.message.includes('ECONNREFUSED')) {
      console.log('')
      console.log('💡 Solution: Make sure the trading bot is running:')
      console.log('   docker compose -f docker-compose.dev.yml up')
    }
  }
}

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

module.exports = { testRealDriftOrder }
