#!/usr/bin/env node

/**
 * Test script to validate the unified trading endpoint with Drift integration
 * This will test both simulation and live trading modes
 */

const API_BASE = 'http://localhost:3000'

async function testUnifiedTradingEndpoint() {
  console.log('🧪 Testing Unified Trading Endpoint with Drift Integration')
  console.log('=' + '='.repeat(60))

  // Test 1: Simulation trade with Drift
  console.log('\n🎯 Test 1: Drift Simulation Trade')
  await testTrade({
    symbol: 'SOL-PERP',
    side: 'BUY',
    amount: 0.01,
    leverage: 5,
    dexProvider: 'DRIFT',
    mode: 'SIMULATION'
  })

  // Test 2: Simulation trade with Jupiter
  console.log('\n🎯 Test 2: Jupiter Simulation Trade')
  await testTrade({
    symbol: 'SOL',
    side: 'BUY',
    amount: 0.01,
    dexProvider: 'JUPITER',
    mode: 'SIMULATION'
  })

  // Test 3: Live trade with Drift (small amount)
  console.log('\n🎯 Test 3: Drift Live Trade (Small Amount)')
  await testTrade({
    symbol: 'SOL-PERP',
    side: 'BUY',
    amount: 0.001, // Very small amount for safety
    leverage: 2,
    dexProvider: 'DRIFT',
    mode: 'LIVE'
  })

  console.log('\n✅ All tests completed!')
}

async function testTrade(tradeParams) {
  try {
    console.log(`  📊 Trading ${tradeParams.amount} ${tradeParams.symbol} via ${tradeParams.dexProvider} (${tradeParams.mode})`)
    
    const response = await fetch(`${API_BASE}/api/automation/trade`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(tradeParams)
    })

    if (!response.ok) {
      const error = await response.text()
      console.log(`  ❌ Request failed: ${response.status} - ${error}`)
      return
    }

    const result = await response.json()
    
    if (result.success) {
      console.log(`  ✅ Trade successful!`)
      console.log(`     Transaction ID: ${result.txId || result.transactionId || 'N/A'}`)
      console.log(`     Execution Price: ${result.executionPrice || 'N/A'}`)
      console.log(`     Provider: ${result.provider || tradeParams.dexProvider}`)
      
      if (result.balance) {
        console.log(`     Updated Balance: ${result.balance} USDC`)
      }
    } else {
      console.log(`  ❌ Trade failed: ${result.error || 'Unknown error'}`)
    }
    
  } catch (error) {
    console.log(`  ❌ Test error: ${error.message}`)
  }
}

// Test automation config format
async function testAutomationConfig() {
  console.log('\n🧪 Testing Automation Config Format')
  console.log('=' + '='.repeat(40))

  const testConfig = {
    userId: 'test_user',
    mode: 'SIMULATION',
    symbol: 'SOL-PERP',
    timeframe: '5m',
    tradingAmount: 100,
    maxLeverage: 10,
    stopLossPercent: 2,
    takeProfitPercent: 6,
    maxDailyTrades: 5,
    riskPercentage: 2,
    dexProvider: 'DRIFT'
  }

  console.log('📋 Sample automation config:')
  console.log(JSON.stringify(testConfig, null, 2))
  console.log('\n✅ Config format validated!')
}

// Run tests
async function main() {
  await testAutomationConfig()
  
  // Check if server is running
  try {
    const healthCheck = await fetch(`${API_BASE}/api/health`).catch(() => null)
    if (!healthCheck || !healthCheck.ok) {
      console.log('\n⚠️  Server not running. Please start the development server first:')
      console.log('   npm run dev')
      return
    }
  } catch (error) {
    console.log('\n⚠️  Could not connect to server. Please ensure it\'s running.')
    return
  }

  await testUnifiedTradingEndpoint()
}

if (require.main === module) {
  main().catch(console.error)
}
