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

async function analyzeOldTrades() {
  const prisma = new PrismaClient();
  
  try {
    console.log('🔍 Analyzing trade data in database...\n');
    
    // Count total trades
    const totalTrades = await prisma.trades.count();
    console.log('📊 Total trades in database:', totalTrades);
    
    // Count by status
    const tradesByStatus = await prisma.trades.groupBy({
      by: ['status'],
      _count: {
        status: true
      }
    });
    
    console.log('\n📈 Trades by status:');
    tradesByStatus.forEach(group => {
      console.log(`  ${group.status}: ${group._count.status} trades`);
    });
    
    // Find oldest and newest trades
    const oldestTrade = await prisma.trades.findFirst({
      orderBy: { createdAt: 'asc' },
      select: { createdAt: true, symbol: true, status: true }
    });
    
    const newestTrade = await prisma.trades.findFirst({
      orderBy: { createdAt: 'desc' },
      select: { createdAt: true, symbol: true, status: true }
    });
    
    console.log('\n⏰ Trade age range:');
    if (oldestTrade) {
      console.log('  Oldest:', oldestTrade.createdAt, '-', oldestTrade.symbol, '-', oldestTrade.status);
    }
    if (newestTrade) {
      console.log('  Newest:', newestTrade.createdAt, '-', newestTrade.symbol, '-', newestTrade.status);
    }
    
    // Count trades older than 30 days
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    
    const oldTrades = await prisma.trades.count({
      where: {
        createdAt: {
          lt: thirtyDaysAgo
        }
      }
    });
    
    console.log(`\n🗓️ Trades older than 30 days: ${oldTrades} (${((oldTrades/totalTrades)*100).toFixed(1)}%)`);
    
    // Count currently open trades
    const openTrades = await prisma.trades.count({
      where: {
        status: 'open'
      }
    });
    
    console.log(`\n🔴 Currently open trades: ${openTrades}`);
    
    if (openTrades > 0) {
      const openTradeDetails = await prisma.trades.findMany({
        where: { status: 'open' },
        select: { 
          id: true, 
          symbol: true, 
          side: true, 
          amount: true, 
          price: true, 
          createdAt: true 
        },
        orderBy: { createdAt: 'desc' }
      });
      
      console.log('\n📋 Open trade details:');
      openTradeDetails.forEach(trade => {
        console.log(`  ${trade.id}: ${trade.side} ${trade.amount} ${trade.symbol} @ $${trade.price} (${trade.createdAt})`);
      });
    }
    
  } catch (error) {
    console.error('❌ Error analyzing trades:', error);
  } finally {
    await prisma.$disconnect();
  }
}

analyzeOldTrades().catch(console.error);
