const priceMonitorService = require('./lib/price-monitor').default;
const { automationService } = require('./lib/automation-service-simple');

async function testPriceMonitorIntegration() {
  console.log('🧪 Testing Price Monitor Integration...\n');

  try {
    // Test 1: Start price monitoring
    console.log('📊 Starting price monitoring...');
    await priceMonitorService.startMonitoring();
    console.log('✅ Price monitoring started\n');

    // Test 2: Check monitoring status
    console.log('🔍 Checking monitoring status...');
    const isMonitoring = priceMonitorService.isMonitoring();
    console.log(`Status: ${isMonitoring ? '🟢 Active' : '🔴 Inactive'}\n`);

    // Test 3: Get monitoring data
    console.log('📈 Getting monitoring data...');
    const monitoringData = await priceMonitorService.getMonitoringData();
    console.log('Monitoring Data:', {
      trades: monitoringData.trades.length,
      alerts: monitoringData.alerts.length,
      prices: Object.keys(monitoringData.prices).length,
      lastUpdated: monitoringData.lastUpdated
    });
    console.log();

    // Test 4: Simulate a price alert
    console.log('🚨 Testing price alert simulation...');
    priceMonitorService.emit('tp_approach', {
      symbol: 'SOLUSD',
      currentPrice: 190.50,
      targetPrice: 200.00,
      distance: 0.05,
      tradeId: 'test-trade-123'
    });
    
    // Wait a moment for event processing
    await new Promise(resolve => setTimeout(resolve, 1000));
    console.log('✅ Price alert simulation completed\n');

    // Test 5: Test automation service integration
    console.log('🤖 Testing automation service configuration...');
    const testConfig = {
      userId: 'test-user',
      mode: 'SIMULATION',
      symbol: 'SOLUSD',
      timeframe: '1h',
      tradingAmount: 100,
      maxLeverage: 3,
      stopLossPercent: 2,
      takeProfitPercent: 6,
      maxDailyTrades: 5,
      riskPercentage: 2
    };
    
    console.log('Starting automation with test config...');
    const startResult = await automationService.startAutomation(testConfig);
    console.log(`Automation start result: ${startResult ? '✅ Success' : '❌ Failed'}\n`);

    if (startResult) {
      // Wait a moment then stop
      console.log('⏸️ Stopping automation...');
      await new Promise(resolve => setTimeout(resolve, 2000));
      const stopResult = await automationService.stopAutomation();
      console.log(`Automation stop result: ${stopResult ? '✅ Success' : '❌ Failed'}\n`);
    }

    // Test 6: Test API endpoint
    console.log('🌐 Testing price monitor API...');
    try {
      const response = await fetch('http://localhost:9001/api/price-monitor', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });
      
      if (response.ok) {
        const apiData = await response.json();
        console.log('API Response:', {
          success: apiData.success,
          dataKeys: Object.keys(apiData.data || {}),
          message: apiData.message
        });
      } else {
        console.log(`API Error: ${response.status} ${response.statusText}`);
      }
    } catch (error) {
      console.log('API test failed (server might not be running):', error.message);
    }
    console.log();

    // Test 7: Stop monitoring
    console.log('🛑 Stopping price monitoring...');
    await priceMonitorService.stopMonitoring();
    console.log('✅ Price monitoring stopped\n');

    console.log('🎉 All price monitor integration tests completed successfully!');

  } catch (error) {
    console.error('❌ Test failed:', error);
    console.error('Stack trace:', error.stack);
  }
}

// Run the test
if (require.main === module) {
  testPriceMonitorIntegration()
    .then(() => {
      console.log('\n✅ Test suite completed');
      process.exit(0);
    })
    .catch((error) => {
      console.error('\n❌ Test suite failed:', error);
      process.exit(1);
    });
}

module.exports = { testPriceMonitorIntegration };
