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

async function syncAllDriftTrades() {
  try {
    console.log('🔄 Syncing all Drift trades to database...');
    
    // Get all Drift position history
    const driftResponse = await fetch('http://localhost:9001/api/drift/position-history');
    const driftData = await driftResponse.json();
    
    if (!driftData.success || !driftData.trades) {
      throw new Error('Failed to fetch Drift position history');
    }
    
    console.log(`📊 Found ${driftData.trades.length} trades in Drift history`);
    
    for (const driftTrade of driftData.trades) {
      console.log(`🔍 Processing Drift trade: ${driftTrade.id}`);
      
      // Check if trade already exists in database
      const existingTrade = await prisma.trades.findUnique({
        where: { id: driftTrade.id }
      });
      
      if (existingTrade) {
        console.log(`✅ Trade ${driftTrade.id} already exists - updating if needed`);
        
        // Update with latest data if missing profit/outcome
        if (!existingTrade.profit && driftTrade.pnl !== undefined) {
          await prisma.trades.update({
            where: { id: driftTrade.id },
            data: {
              profit: driftTrade.pnl,
              outcome: driftTrade.outcome,
              exitPrice: driftTrade.exitPrice,
              closedAt: driftTrade.exitTime ? new Date(driftTrade.exitTime) : null,
              status: driftTrade.exitPrice ? 'COMPLETED' : 'OPEN'
            }
          });
          console.log(`🔄 Updated trade ${driftTrade.id} with P&L data`);
        }
      } else {
        console.log(`📝 Creating new trade ${driftTrade.id} in database`);
        
        // Create new trade record
        await prisma.trades.create({
          data: {
            id: driftTrade.id,
            userId: 'default-user',
            symbol: 'SOLUSD',
            side: driftTrade.side,
            amount: driftTrade.amount || 1,
            entryPrice: driftTrade.entryPrice,
            exitPrice: driftTrade.exitPrice,
            profit: driftTrade.pnl,
            outcome: driftTrade.outcome,
            status: driftTrade.exitPrice ? 'COMPLETED' : 'OPEN',
            leverage: driftTrade.leverage || 1,
            confidence: 75,
            createdAt: new Date(driftTrade.entryTime),
            closedAt: driftTrade.exitTime ? new Date(driftTrade.exitTime) : null,
            driftTxId: `DRIFT_${driftTrade.id}`,
            tradingMode: 'PERP'
          }
        });
        console.log(`✅ Created trade ${driftTrade.id} in database`);
      }
    }
    
    // Now get all trades with profit data
    const completedTrades = await prisma.trades.findMany({
      where: {
        status: 'COMPLETED',
        profit: { not: null },
        outcome: { not: null }
      },
      orderBy: { closedAt: 'desc' }
    });
    
    console.log(`📈 Total completed trades with profit data: ${completedTrades.length}`);
    
    // Filter out simulations
    const realTrades = completedTrades.filter(trade => {
      return !trade.driftTxId?.startsWith('SIM_') && trade.tradingMode !== 'SIMULATION';
    });
    
    console.log(`📊 Real trades after filtering: ${realTrades.length}`);
    
    realTrades.forEach(trade => {
      console.log(`  💰 ${trade.side} - P&L: $${trade.profit?.toFixed(2)} - ${trade.outcome}`);
    });
    
    const totalPnL = realTrades.reduce((sum, trade) => sum + (trade.profit || 0), 0);
    const wins = realTrades.filter(t => (t.profit || 0) > 0).length;
    const winRate = realTrades.length > 0 ? (wins / realTrades.length * 100) : 0;
    
    console.log(`📈 Summary: ${realTrades.length} trades, ${wins} wins, ${winRate.toFixed(1)}% win rate, $${totalPnL.toFixed(2)} total P&L`);
    
  } catch (error) {
    console.error('❌ Error syncing Drift trades:', error);
  } finally {
    await prisma.$disconnect();
  }
}

syncAllDriftTrades();
