#!/usr/bin/env node

/**
 * Test script to verify orphaned order cleanup integration
 * Tests the position monitor's ability to trigger cleanup when no positions detected
 */

async function testOrphanedCleanupIntegration() {
  console.log('🧪 Testing Orphaned Order Cleanup Integration')
  console.log('=' .repeat(60))
  
  try {
    // Test the position monitor endpoint
    console.log('📡 Testing position monitor endpoint...')
    
    const response = await fetch('http://localhost:3000/api/automation/position-monitor', {
      cache: 'no-store',
      headers: {
        'Cache-Control': 'no-cache'
      }
    })
    
    if (!response.ok) {
      throw new Error(`Position monitor API failed: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    
    console.log('📊 Position Monitor Result:')
    console.log('  - Has Position:', result.hasPosition)
    console.log('  - Risk Level:', result.riskLevel)
    console.log('  - Next Action:', result.nextAction)
    
    // Check if orphaned order cleanup was triggered
    if (result.orphanedOrderCleanup) {
      console.log('\n🧹 Orphaned Order Cleanup:')
      console.log('  - Triggered:', result.orphanedOrderCleanup.triggered)
      console.log('  - Success:', result.orphanedOrderCleanup.success)
      console.log('  - Message:', result.orphanedOrderCleanup.message)
      
      if (result.orphanedOrderCleanup.summary) {
        console.log('  - Summary:', result.orphanedOrderCleanup.summary)
      }
      
      if (result.orphanedOrderCleanup.error) {
        console.log('  - Error:', result.orphanedOrderCleanup.error)
      }
    }
    
    // Test cleanup API directly if position monitor shows no position
    if (!result.hasPosition) {
      console.log('\n🔧 Testing direct cleanup API...')
      
      const cleanupResponse = await fetch('http://localhost:3000/api/drift/cleanup-orders', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      })
      
      if (cleanupResponse.ok) {
        const cleanupResult = await cleanupResponse.json()
        
        console.log('✅ Direct cleanup API response:')
        console.log('  - Success:', cleanupResult.success)
        
        if (cleanupResult.summary) {
          console.log('  - Active Positions:', cleanupResult.summary.activePositions)
          console.log('  - Active Orders:', cleanupResult.summary.activeOrders)
          console.log('  - Orphaned Orders:', cleanupResult.summary.orphanedOrders)
          console.log('  - Total Canceled:', cleanupResult.summary.totalCanceled)
        }
        
        if (cleanupResult.error) {
          console.log('  - Error:', cleanupResult.error)
        }
      } else {
        console.log('❌ Direct cleanup API failed:', cleanupResponse.status)
      }
    }
    
    console.log('\n✅ Integration test completed successfully!')
    console.log('\n📋 Integration Summary:')
    console.log('  - Position monitoring automatically checks for orphaned orders')
    console.log('  - Cleanup only triggers when no positions detected')
    console.log('  - Eliminates need for redundant polling timers')
    console.log('  - Provides detailed feedback on cleanup operations')
    
  } catch (error) {
    console.error('❌ Integration test failed:', error)
    console.log('\n🔍 Troubleshooting:')
    console.log('  - Ensure the Next.js server is running (npm run dev)')
    console.log('  - Check that all APIs are accessible')
    console.log('  - Verify Drift environment configuration')
  }
}

// Self-executing async function
;(async () => {
  await testOrphanedCleanupIntegration()
})()
