#!/usr/bin/env node

/**
 * Position Consolidation Test
 * Cleans up fragmented orders and creates simple 3-order structure
 */

async function testConsolidation() {
  console.log('🧹 TESTING POSITION CONSOLIDATION');
  console.log('='.repeat(50));
  
  try {
    // 1. Get current position
    console.log('1️⃣ Fetching current position...');
    const positionResponse = await fetch('http://localhost:9001/api/drift/positions');
    const positionData = await positionResponse.json();
    
    if (!positionData.success || !positionData.positions.length) {
      console.log('❌ No active positions found');
      return;
    }
    
    const position = positionData.positions[0];
    console.log(`   📊 Position: ${position.side.toUpperCase()} ${position.size} ${position.symbol}`);
    console.log(`   💰 Entry: $${position.entryPrice.toFixed(4)}`);
    console.log(`   📈 Current: $${(position.markPrice || position.entryPrice).toFixed(4)}`);
    console.log(`   💸 P&L: $${position.unrealizedPnl.toFixed(2)}`);
    
    // 2. Get current orders count
    console.log('\n2️⃣ Checking current orders...');
    const ordersResponse = await fetch('http://localhost:9001/api/drift/orders');
    const ordersData = await ordersResponse.json();
    const activeOrders = ordersData.orders.filter(o => o.status === 'OPEN');
    console.log(`   📋 Active orders: ${activeOrders.length}`);
    
    // 3. Calculate consolidated levels
    console.log('\n3️⃣ Calculating consolidated levels...');
    const entryPrice = position.entryPrice;
    const size = position.size;
    const side = position.side.toLowerCase();
    
    // Dynamic levels based on position
    const stopLossPercent = 1.5; // 1.5% protective stop
    const tp1Percent = 2.6; // 2.6% first target  
    const tp2Percent = 4.2; // 4.2% extended target
    
    let stopLoss, takeProfit1, takeProfit2;
    
    if (side === 'long') {
      stopLoss = entryPrice * (1 - stopLossPercent / 100);
      takeProfit1 = entryPrice * (1 + tp1Percent / 100);
      takeProfit2 = entryPrice * (1 + tp2Percent / 100);
    } else {
      stopLoss = entryPrice * (1 + stopLossPercent / 100);
      takeProfit1 = entryPrice * (1 - tp1Percent / 100);
      takeProfit2 = entryPrice * (1 - tp2Percent / 100);
    }
    
    const tp1Size = Math.floor(size * 0.7 * 100) / 100; // 70%
    const tp2Size = size - tp1Size; // 30%
    
    console.log(`   🛑 Stop Loss: $${stopLoss.toFixed(4)} (${stopLossPercent}% risk)`);
    console.log(`   🎯 Take Profit 1: $${takeProfit1.toFixed(4)} (${tp1Percent}% gain) - ${tp1Size} SOL`);
    console.log(`   🚀 Take Profit 2: $${takeProfit2.toFixed(4)} (${tp2Percent}% gain) - ${tp2Size} SOL`);
    console.log(`   ⚖️ Risk/Reward: ${(tp1Percent / stopLossPercent).toFixed(1)}:1`);
    
    // 4. Show consolidation plan
    console.log('\n4️⃣ CONSOLIDATION PLAN:');
    console.log('   📉 BEFORE: 24+ fragmented orders');
    console.log('   📈 AFTER: 3 clean orders');
    console.log('   ✅ Benefits:');
    console.log('      • Clear risk management');
    console.log('      • Lower transaction costs');
    console.log('      • Better profit optimization');
    console.log('      • Easier monitoring');
    
    console.log('\n💡 RECOMMENDED NEXT STEPS:');
    console.log('1. Cancel all existing orders');
    console.log('2. Place single stop loss for full position');
    console.log('3. Place two take profit orders (70%/30% split)');
    
    return {
      success: true,
      currentOrders: activeOrders.length,
      consolidatedOrders: 3,
      position: {
        symbol: position.symbol,
        side: position.side,
        size: position.size,
        entryPrice: position.entryPrice
      },
      levels: {
        stopLoss,
        takeProfit1,
        takeProfit2,
        tp1Size,
        tp2Size
      }
    };
    
  } catch (error) {
    console.error('❌ Consolidation test failed:', error.message);
    return { success: false, error: error.message };
  }
}

// Run the test
testConsolidation().then(result => {
  if (result.success) {
    console.log('\n✅ CONSOLIDATION ANALYSIS COMPLETE');
    console.log(`📊 Reduction: ${result.currentOrders} → ${result.consolidatedOrders} orders`);
  }
}).catch(console.error);
