#!/usr/bin/env node

/**
 * Test script for Drift order cleanup system
 * Tests both manual and automated cleanup functionality
 */

const { driftOrderCleanupService } = require('./lib/drift-order-cleanup-service.js')

async function testCleanupSystem() {
  console.log('🧪 Testing Drift Order Cleanup System')
  console.log('=====================================\n')

  try {
    // Test 1: Check current status
    console.log('📊 Test 1: Service Status Check')
    const initialStatus = driftOrderCleanupService.getStatus()
    console.log('Initial status:', initialStatus)
    console.log()

    // Test 2: Manual cleanup
    console.log('🧹 Test 2: Manual Cleanup')
    try {
      const manualResult = await driftOrderCleanupService.forceCleanup()
      console.log('Manual cleanup result:', manualResult.summary)
    } catch (error) {
      console.log('Manual cleanup error (expected if no orders):', error.message)
    }
    console.log()

    // Test 3: Check positions and orders directly
    console.log('📊 Test 3: Direct API Check')
    
    try {
      const [positionsRes, ordersRes] = await Promise.all([
        fetch('http://localhost:9001/api/drift/positions'),
        fetch('http://localhost:9001/api/drift/orders')
      ])

      if (positionsRes.ok && ordersRes.ok) {
        const positions = await positionsRes.json()
        const orders = await ordersRes.json()

        console.log(`Current positions: ${positions.positions?.length || 0}`)
        console.log(`Current orders: ${orders.orders?.length || 0}`)

        if (positions.positions?.length > 0) {
          console.log('Active positions:')
          positions.positions.forEach(pos => {
            console.log(`  - ${pos.symbol}: Size ${pos.size}, Value $${pos.value?.toFixed(2) || 'N/A'}`)
          })
        }

        if (orders.orders?.length > 0) {
          console.log('Active orders:')
          orders.orders.forEach(order => {
            console.log(`  - ${order.symbol}: ${order.side} ${order.size} @ $${order.price} (${order.orderType})`)
          })
        }
      } else {
        console.log('❌ Failed to fetch positions/orders')
      }
    } catch (error) {
      console.log('API check error:', error.message)
    }
    console.log()

    // Test 4: Start automated monitoring (briefly)
    console.log('🤖 Test 4: Automated Monitoring')
    console.log('Starting automated cleanup service for 30 seconds...')
    
    driftOrderCleanupService.start(10000) // Check every 10 seconds
    
    // Let it run for 30 seconds
    await new Promise(resolve => setTimeout(resolve, 30000))
    
    console.log('Stopping automated service...')
    driftOrderCleanupService.stop()

    // Final status
    const finalStatus = driftOrderCleanupService.getStatus()
    console.log('Final status:', finalStatus)

    console.log('\n✅ Test completed successfully!')
    console.log('\nNext steps:')
    console.log('1. The cleanup service is now available via driftOrderCleanupService')
    console.log('2. Call .start() to begin automated monitoring')
    console.log('3. Call .forceCleanup() for manual cleanup')
    console.log('4. Call .stop() to stop monitoring')
    console.log('5. Integration with main trading bot recommended')

  } catch (error) {
    console.error('❌ Test failed:', error)
    process.exit(1)
  }
}

// Run test if called directly
if (require.main === module) {
  testCleanupSystem().catch(console.error)
}

module.exports = { testCleanupSystem }
