#!/usr/bin/env node

/**
 * Test script for Drift trading login and account functionality
 */

require('dotenv').config() // Load environment variables
const BASE_URL = 'http://localhost:9001'

async function testDriftLogin() {
  console.log('🔐 Testing Drift login...')
  
  try {
    const response = await fetch(`${BASE_URL}/api/drift/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    })
    
    const result = await response.json()
    console.log('Login result:', JSON.stringify(result, null, 2))
    
    if (result.isLoggedIn) {
      console.log('✅ Login successful!')
      console.log(`📍 Public Key: ${result.publicKey}`)
      console.log(`👤 User Account Exists: ${result.userAccountExists}`)
      return true
    } else {
      console.log('❌ Login failed:', result.error)
      return false
    }
  } catch (error) {
    console.error('❌ Login test failed:', error.message)
    return false
  }
}

async function testAccountBalance() {
  console.log('\n💰 Testing account balance retrieval...')
  
  try {
    const response = await fetch(`${BASE_URL}/api/drift/balance`)
    const result = await response.json()
    
    if (response.ok) {
      console.log('✅ Balance retrieved successfully!')
      console.log('Account Balance:', JSON.stringify(result, null, 2))
      console.log(`💵 Total Collateral: $${result.totalCollateral.toFixed(2)}`)
      console.log(`🆓 Free Collateral: $${result.freeCollateral.toFixed(2)}`)
      console.log(`📊 Margin Requirement: $${result.marginRequirement.toFixed(2)}`)
      console.log(`📈 Account Value: $${result.accountValue.toFixed(2)}`)
      console.log(`⚖️ Leverage: ${result.leverage.toFixed(2)}x`)
      console.log(`💸 Available Balance: $${result.availableBalance.toFixed(2)}`)
      return true
    } else {
      console.log('❌ Balance retrieval failed:', result.error)
      return false
    }
  } catch (error) {
    console.error('❌ Balance test failed:', error.message)
    return false
  }
}

async function testPositions() {
  console.log('\n📊 Testing positions retrieval...')
  
  try {
    const response = await fetch(`${BASE_URL}/api/drift/positions`)
    const result = await response.json()
    
    if (response.ok) {
      console.log('✅ Positions retrieved successfully!')
      
      if (result.positions.length === 0) {
        console.log('📋 No open positions found')
      } else {
        console.log(`📋 Found ${result.positions.length} position(s):`)
        result.positions.forEach((pos, index) => {
          console.log(`\n  Position ${index + 1}:`)
          console.log(`    Symbol: ${pos.symbol}`)
          console.log(`    Side: ${pos.side}`)
          console.log(`    Size: ${pos.size}`)
          console.log(`    Entry Price: $${pos.entryPrice}`)
          console.log(`    Mark Price: $${pos.markPrice}`)
          console.log(`    Unrealized PnL: $${pos.unrealizedPnl.toFixed(2)}`)
          console.log(`    Market Index: ${pos.marketIndex}`)
          console.log(`    Market Type: ${pos.marketType}`)
        })
      }
      return true
    } else {
      console.log('❌ Positions retrieval failed:', result.error)
      return false
    }
  } catch (error) {
    console.error('❌ Positions test failed:', error.message)
    return false
  }
}

async function runTests() {
  console.log('🚀 Starting Drift Trading Tests...\n')
  
  // Test 1: Login
  const loginSuccess = await testDriftLogin()
  
  if (loginSuccess) {
    // Test 2: Account Balance (only if login succeeded)
    await testAccountBalance()
    
    // Test 3: Positions (only if login succeeded)
    await testPositions()
  }
  
  console.log('\n✨ Tests completed!')
}

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

module.exports = { testDriftLogin, testAccountBalance, testPositions }
