#!/usr/bin/env node

/**
 * Test position checking in automation service
 * This script tests that the automation respects open positions
 */

import { automationService } from './lib/automation-service-simple.js'

async function testPositionChecking() {
  console.log('🧪 Testing Position Checking Logic...')
  
  try {
    // Test 1: Check hasOpenPositions method
    console.log('\n1️⃣ Testing hasOpenPositions method...')
    const hasPositions = await automationService.hasOpenPositions()
    console.log(`✅ hasOpenPositions() result: ${hasPositions}`)
    
    // Test 2: Test automation start with position check
    console.log('\n2️⃣ Testing automation start with position check...')
    
    const testConfig = {
      userId: 'test-position-check',
      mode: 'SIMULATION',
      symbol: 'SOLUSD',
      selectedTimeframes: ['1h'],
      tradingAmount: 10,
      maxDailyTrades: 1,
      dexProvider: 'DRIFT'
    }
    
    // Try to start automation (should check positions)
    const startResult = await automationService.startAutomation(testConfig)
    console.log(`✅ Start automation result: ${startResult}`)
    
    // Test 3: Check automation status
    console.log('\n3️⃣ Testing automation status...')
    const status = await automationService.getStatus()
    console.log('📊 Automation status:', {
      isRunning: status?.isRunning,
      hasPositions: status?.hasOpenPositions,
      message: status?.message || 'No message'
    })
    
    // Test 4: Stop automation
    console.log('\n4️⃣ Stopping automation...')
    const stopResult = await automationService.stopAutomation()
    console.log(`✅ Stop result: ${stopResult}`)
    
    console.log('\n🎉 Position checking tests completed!')
    
  } catch (error) {
    console.error('❌ Test failed:', error)
    console.error('Stack:', error.stack)
  }
}

// Run the test
testPositionChecking()
  .then(() => {
    console.log('✅ Test script completed')
    process.exit(0)
  })
  .catch((error) => {
    console.error('❌ Test script failed:', error)
    process.exit(1)
  })
