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

const prisma = new PrismaClient();

async function recordRecentTrade() {
  try {
    console.log('📝 Recording recent trade from Drift Position History...');
    
    // Data from the screenshot: 14 minutes ago stop loss
    const tradeData = {
      id: `drift_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      userId: 'user_main',
      symbol: 'SOL-PERP',
      side: 'LONG',
      amount: 5.34, // 5.34 SOL from screenshot
      price: 184.265, // Entry price from screenshot
      entryPrice: 184.265,
      exitPrice: 182, // Exit price from screenshot  
      stopLoss: null,
      takeProfit: null,
      leverage: 1,
      profit: -12.34, // P&L from screenshot
      pnlPercent: (-12.34 / (5.34 * 184.265)) * 100, // Calculate percentage
      outcome: 'LOSS',
      status: 'COMPLETED',
      confidence: null,
      aiAnalysis: 'Manual stop loss execution - trade recorded from Drift position history',
      isAutomated: false,
      tradingMode: 'PERP',
      driftTxId: `DRIFT_MANUAL_${Date.now()}`,
      executedAt: new Date(Date.now() - 14 * 60 * 1000), // 14 minutes ago
      closedAt: new Date(Date.now() - 14 * 60 * 1000), // Same time
      createdAt: new Date(Date.now() - 14 * 60 * 1000),
      updatedAt: new Date()
    };

    console.log('📊 Trade details:');
    console.log(`  Symbol: ${tradeData.symbol}`);
    console.log(`  Side: ${tradeData.side}`);
    console.log(`  Amount: ${tradeData.amount} SOL`);
    console.log(`  Entry: $${tradeData.entryPrice}`);
    console.log(`  Exit: $${tradeData.exitPrice}`);
    console.log(`  P&L: $${tradeData.profit}`);
    console.log(`  P&L %: ${tradeData.pnlPercent.toFixed(2)}%`);

    // Check if this trade already exists
    const existingTrade = await prisma.trades.findFirst({
      where: {
        amount: tradeData.amount,
        entryPrice: tradeData.entryPrice,
        profit: tradeData.profit,
        createdAt: {
          gte: new Date(Date.now() - 30 * 60 * 1000) // Within last 30 minutes
        }
      }
    });

    if (existingTrade) {
      console.log('⚠️  Trade already exists:', existingTrade.id);
      return existingTrade;
    }

    // Create the trade record
    const newTrade = await prisma.trades.create({
      data: tradeData
    });

    console.log('✅ Successfully recorded trade:', newTrade.id);

    // Get updated statistics
    const allTrades = await prisma.trades.findMany({
      where: {
        status: { in: ['COMPLETED', 'EXECUTED'] },
        tradingMode: { not: 'SIMULATION' },
        driftTxId: { not: { startsWith: 'SIM_' } }
      }
    });

    const completedTrades = allTrades.filter(t => t.profit !== null);
    const totalPnl = completedTrades.reduce((sum, t) => sum + (t.profit || 0), 0);
    const wins = completedTrades.filter(t => t.profit > 0);
    const losses = completedTrades.filter(t => t.profit < 0);

    console.log('\n📈 Updated Statistics:');
    console.log(`Total Trades: ${completedTrades.length}`);
    console.log(`Wins: ${wins.length}, Losses: ${losses.length}`);
    console.log(`Win Rate: ${((wins.length / completedTrades.length) * 100).toFixed(1)}%`);
    console.log(`Total P&L: $${totalPnl.toFixed(2)}`);

    return newTrade;

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

recordRecentTrade();
