#!/usr/bin/env node

/**
 * Calculate Drift Protocol Minimum Order Size
 * Based on the error: base_asset_amount=2730661 cannot be below order_step_size=10000000
 */

async function calculateMinimumOrderSize() {
  console.log('🧮 CALCULATING DRIFT PROTOCOL MINIMUM ORDER SIZE')
  console.log('=' .repeat(60))
  
  // From the error log:
  // Our $0.50 order = 2730661 units
  // Required minimum = 10000000 units
  
  const ourOrderUnits = 2730661
  const requiredMinimumUnits = 10000000
  const ourOrderUsd = 0.50
  
  // Calculate what $1 USD equals in units
  const unitsPerDollar = ourOrderUnits / ourOrderUsd
  console.log('📊 Units per $1 USD:', unitsPerDollar.toLocaleString())
  
  // Calculate minimum USD amount needed
  const minimumUsdRequired = requiredMinimumUnits / unitsPerDollar
  console.log('💰 Minimum USD amount required: $' + minimumUsdRequired.toFixed(2))
  
  // Calculate safety margin (add 10%)
  const safeMinimum = minimumUsdRequired * 1.1
  console.log('🛡️ Safe minimum (110%): $' + safeMinimum.toFixed(2))
  
  console.log('')
  console.log('🎯 TESTING RECOMMENDATIONS:')
  console.log('  1. Use minimum $' + Math.ceil(safeMinimum) + ' for testing')
  console.log('  2. This will allow testing percentage limits properly')
  console.log('  3. Previous tests failed due to order size, not percentages')
  
  return {
    minimumUsd: minimumUsdRequired,
    safeMinimum: safeMinimum,
    recommendedTestAmount: Math.ceil(safeMinimum)
  }
}

async function testWithProperOrderSize() {
  console.log('')
  console.log('🚀 TESTING WITH PROPER ORDER SIZE')
  console.log('=' .repeat(50))
  
  const calc = await calculateMinimumOrderSize()
  
  const testOrder = {
    action: 'place_order',
    symbol: 'SOL',
    side: 'buy',
    amount: calc.recommendedTestAmount,
    leverage: 1,
    stopLoss: true,
    takeProfit: true,
    stopLossPercent: 0.5,   // Test ultra-tight 0.5%
    takeProfitPercent: 0.25  // Test ultra-tight 0.25%
  }
  
  console.log('📋 Test Order with Proper Size:')
  console.log('  Amount: $' + testOrder.amount)
  console.log('  Stop Loss: ' + testOrder.stopLossPercent + '%')
  console.log('  Take Profit: ' + testOrder.takeProfitPercent + '%')
  console.log('')
  
  if (!process.argv.includes('--execute')) {
    console.log('💡 Add --execute flag to place this real order')
    console.log('   Example: node minimum-order-calculator.js --execute')
    return
  }
  
  console.log('🚀 Placing order with proper size...')
  
  try {
    const response = await fetch('http://localhost:3000/api/drift/trade', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(testOrder)
    })
    
    const result = await response.json()
    
    if (result.result && result.result.success) {
      console.log('✅ ORDER PLACED SUCCESSFULLY!')
      console.log('🔗 Transaction ID:', result.result.transactionId)
      console.log('🎯 MINIMUM PERCENTAGES CONFIRMED:')
      console.log('  ✅ Stop Loss: 0.5% works!')
      console.log('  ✅ Take Profit: 0.25% works!')
    } else {
      console.log('❌ Order failed:')
      console.log(JSON.stringify(result, null, 2))
    }
    
  } catch (error) {
    console.error('❌ Test failed:', error.message)
  }
}

if (require.main === module) {
  if (process.argv.includes('--execute')) {
    testWithProperOrderSize()
  } else {
    calculateMinimumOrderSize()
  }
}

module.exports = { calculateMinimumOrderSize, testWithProperOrderSize }
