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

const prisma = new PrismaClient();

async function fixTradeAmounts() {
  try {
    console.log('🔍 Finding trades with unrealistic amounts...');
    
    // Find trades that are too large for a $240 account
    const largeTrades = await prisma.trades.findMany({
      where: {
        amount: { gt: 10 } // More than 10 SOL (~$1,800) is unrealistic for $240 account
      },
      select: { 
        id: true, 
        amount: true, 
        entryPrice: true, 
        exitPrice: true, 
        profit: true, 
        side: true,
        createdAt: true
      }
    });

    console.log(`Found ${largeTrades.length} trades with unrealistic amounts`);

    if (largeTrades.length === 0) {
      console.log('✅ No trades need fixing');
      return;
    }

    // Scale down amounts to realistic levels
    const updates = [];
    for (const trade of largeTrades) {
      const originalPositionValue = trade.amount * trade.entryPrice;
      
      // Scale to realistic amount (max $200 position for $240 account)
      const maxPositionValue = 200; // $200 max position
      const scaleFactor = maxPositionValue / originalPositionValue;
      
      const newAmount = parseFloat((trade.amount * scaleFactor).toFixed(6));
      const newProfit = parseFloat((trade.profit * scaleFactor).toFixed(2));
      
      console.log(`📊 Trade ${trade.id.substring(0, 8)}...:`);
      console.log(`   Original: ${trade.amount} SOL ($${originalPositionValue.toFixed(2)}) → $${trade.profit}`);
      console.log(`   Scaled:   ${newAmount} SOL ($${(newAmount * trade.entryPrice).toFixed(2)}) → $${newProfit}`);
      
      updates.push({
        id: trade.id,
        amount: newAmount,
        profit: newProfit
      });
    }

    // Apply updates
    console.log(`\n🔄 Updating ${updates.length} trades...`);
    for (const update of updates) {
      await prisma.trades.update({
        where: { id: update.id },
        data: {
          amount: update.amount,
          profit: update.profit
        }
      });
    }

    console.log('✅ Trade amounts fixed successfully!');
    
    // Show summary
    const newStats = await prisma.trades.aggregate({
      where: { status: { in: ['COMPLETED', 'EXECUTED'] } },
      _sum: { profit: true },
      _count: { id: true }
    });

    const winningTrades = await prisma.trades.count({
      where: { 
        status: { in: ['COMPLETED', 'EXECUTED'] },
        profit: { gt: 0 }
      }
    });

    console.log('\n📈 Updated Statistics:');
    console.log(`Total Trades: ${newStats._count.id}`);
    console.log(`Winning Trades: ${winningTrades}`);
    console.log(`Win Rate: ${((winningTrades / newStats._count.id) * 100).toFixed(1)}%`);
    console.log(`Total P&L: $${newStats._sum.profit?.toFixed(2) || '0.00'}`);

  } catch (error) {
    console.error('❌ Error fixing trade amounts:', error.message);
  } finally {
    await prisma.$disconnect();
  }
}

fixTradeAmounts();
