#!/usr/bin/env node

/**
 * Test script to verify orphaned order cleanup functionality
 */

async function testOrphanedOrderCleanup() {
  console.log('🧪 TESTING: Orphaned Order Cleanup Functionality\n');
  
  const baseUrl = process.env.INTERNAL_API_URL || 'http://localhost:3000';
  
  try {
    // 1. Check current orders
    console.log('1. Checking current order status...');
    const ordersResponse = await fetch(`${baseUrl}/api/drift/orders`);
    const ordersData = await ordersResponse.json();
    
    if (ordersData.success) {
      console.log(`📊 Current orders: ${ordersData.orders?.length || 0}`);
      console.log(`📊 Active orders: ${ordersData.totalActiveOrders || 0}`);
      
      if (ordersData.totalActiveOrders > 0) {
        console.log('   Found orders to clean up');
        ordersData.orders.slice(0, 3).forEach((order, idx) => {
          console.log(`   ${idx + 1}. Order ${order.orderId} - ${JSON.stringify(order.status)} - ${order.baseAssetAmount}`);
        });
      } else {
        console.log('   No active orders found');
      }
    }
    
    // 2. Check current positions
    console.log('\n2. Checking current positions...');
    const positionsResponse = await fetch(`${baseUrl}/api/drift/positions`);
    const positionsData = await positionsResponse.json();
    
    if (positionsData.success) {
      console.log(`📊 Active positions: ${positionsData.positions?.length || 0}`);
      if (positionsData.positions?.length > 0) {
        positionsData.positions.forEach((pos, idx) => {
          console.log(`   ${idx + 1}. ${pos.symbol} ${pos.side.toUpperCase()} ${pos.size} @ $${pos.entryPrice.toFixed(4)}`);
        });
      } else {
        console.log('   No active positions found');
      }
    }
    
    // 3. Test cleanup-orders endpoint
    console.log('\n3. Testing cleanup-orders endpoint...');
    const cleanupResponse = await fetch(`${baseUrl}/api/drift/cleanup-orders`, {
      method: 'POST'
    });
    
    if (cleanupResponse.ok) {
      const cleanupResult = await cleanupResponse.json();
      console.log('✅ Cleanup-orders endpoint successful');
      console.log(`📊 Summary:`, cleanupResult.summary);
      console.log(`📋 Message: ${cleanupResult.message}`);
      
      if (cleanupResult.summary?.totalCanceled > 0) {
        console.log(`🧹 Cleaned up ${cleanupResult.summary.totalCanceled} orders`);
      }
      
      if (cleanupResult.summary?.activeOrders > 0) {
        console.log(`⚠️ ${cleanupResult.summary.activeOrders} orders still remain after cleanup`);
      }
    } else {
      console.error(`❌ Cleanup-orders failed: ${cleanupResponse.status}`);
      const errorText = await cleanupResponse.text();
      console.error(`Error details: ${errorText}`);
    }
    
    // 4. Test cancel-all-orders endpoint if needed
    if (ordersData.totalActiveOrders > 0) {
      console.log('\n4. Testing cancel-all-orders endpoint...');
      const cancelAllResponse = await fetch(`${baseUrl}/api/drift/cancel-all-orders`, {
        method: 'POST'
      });
      
      if (cancelAllResponse.ok) {
        const cancelAllResult = await cancelAllResponse.json();
        console.log('✅ Cancel-all-orders endpoint successful');
        console.log(`📊 Total canceled: ${cancelAllResult.totalCanceled || 0}`);
        console.log(`📊 Successful: ${cancelAllResult.successfulCancellations || 0}`);
        console.log(`📊 Failed: ${cancelAllResult.failedCancellations || 0}`);
      } else {
        console.error(`❌ Cancel-all-orders failed: ${cancelAllResponse.status}`);
        const errorText = await cancelAllResponse.text();
        console.error(`Error details: ${errorText}`);
      }
    }
    
    // 5. Final verification - check orders again
    console.log('\n5. Final verification - checking orders after cleanup...');
    const finalOrdersResponse = await fetch(`${baseUrl}/api/drift/orders`);
    const finalOrdersData = await finalOrdersResponse.json();
    
    if (finalOrdersData.success) {
      console.log(`📊 Final active orders: ${finalOrdersData.totalActiveOrders || 0}`);
      
      if (finalOrdersData.totalActiveOrders === 0) {
        console.log('✅ SUCCESS: All orders successfully cleaned up!');
      } else {
        console.log(`⚠️ WARNING: ${finalOrdersData.totalActiveOrders} orders still remain`);
        console.log('   This may indicate orders that cannot be canceled (e.g., filled orders)');
      }
    }
    
    console.log('\n✅ Orphaned order cleanup test completed');
    
  } catch (error) {
    console.error('❌ Test failed:', error.message);
    console.error('Full error:', error);
  }
}

// Run the test
testOrphanedOrderCleanup()
  .then(() => {
    console.log('\n🎯 Test execution completed');
  })
  .catch((error) => {
    console.error('❌ Test execution failed:', error);
  });
