const { PrismaClient } = require('@prisma/client');

async function testTradeData() {
  const prisma = new PrismaClient();
  
  try {
    console.log('🔍 Testing trade data queries...\n');
    
    // Get all completed trades with profit/outcome
    const allTrades = await prisma.trades.findMany({
      where: {
        status: 'COMPLETED',
        profit: { not: null },
        outcome: { not: null }
      },
      select: {
        id: true,
        tradingMode: true,
        driftTxId: true,
        profit: true,
        outcome: true,
        symbol: true
      },
      orderBy: { createdAt: 'desc' }
    });
    
    console.log(`📊 Found ${allTrades.length} completed trades with profit/outcome:`);
    
    allTrades.forEach((trade, i) => {
      console.log(`${i + 1}. ${trade.symbol} - ${trade.outcome}`);
      console.log(`   Mode: ${trade.tradingMode}`);
      console.log(`   TxId: ${trade.driftTxId}`);
      console.log(`   Profit: $${trade.profit}`);
      
      // Apply the same filtering logic as the API
      let isSimulation = false;
      
      if (trade.driftTxId && trade.driftTxId.startsWith('SIM_')) {
        isSimulation = true;
        console.log(`   🚫 EXCLUDED: Simulation TxId`);
      } else if (trade.tradingMode === 'SIMULATION') {
        isSimulation = true;
        console.log(`   🚫 EXCLUDED: Simulation Mode`);
      } else {
        console.log(`   ✅ INCLUDED: Real trade`);
      }
      
      console.log('');
    });
    
    // Count real trades
    const realTrades = allTrades.filter(trade => {
      if (trade.driftTxId && trade.driftTxId.startsWith('SIM_')) return false;
      if (trade.tradingMode === 'SIMULATION') return false;
      return true;
    });
    
    console.log(`📈 Summary: ${realTrades.length} real trades out of ${allTrades.length} total`);
    
    if (realTrades.length > 0) {
      console.log('\n🎯 Real Trade Statistics:');
      realTrades.forEach(trade => {
        console.log(`   ${trade.symbol}: ${trade.outcome} ($${trade.profit})`);
      });
      
      const wins = realTrades.filter(t => t.outcome.toUpperCase() === 'WIN');
      const totalPnl = realTrades.reduce((sum, t) => sum + t.profit, 0);
      
      console.log(`\n📊 Stats: ${wins.length} wins / ${realTrades.length} total = ${(wins.length/realTrades.length*100).toFixed(1)}% win rate`);
      console.log(`💰 Total P&L: $${totalPnl.toFixed(2)}`);
    }
    
  } catch (error) {
    console.error('❌ Error:', error.message);
  } finally {
    await prisma.$disconnect();
  }
}

testTradeData();
