// Simple risk management for current position
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function addRiskManagement() {
  try {
    console.log('🛡️ Adding risk management for current position...');
    
    // Check if there's an active position
    const response = await fetch('http://localhost:9001/api/automation/position-monitor');
    const data = await response.json();
    
    if (!data.monitor.hasPosition) {
      console.log('✅ No active position - no risk management needed');
      return;
    }
    
    const position = data.monitor.position;
    console.log('📊 Position:', {
      side: position.side,
      size: position.size,
      entry: position.entryPrice,
      current: position.currentPrice,
      pnl: position.unrealizedPnl
    });
    
    if (position.side === 'short') {
      console.log('📝 For SHORT position:');
      console.log('  - Stop-loss should be ABOVE entry price (to limit losses)');
      console.log('  - Take-profit should be BELOW entry price (to secure gains)');
      
      const stopLoss = (position.entryPrice * 1.05).toFixed(2); // 5% above entry
      const takeProfit = (position.entryPrice * 0.97).toFixed(2); // 3% below entry
      
      console.log(`  - Recommended Stop-Loss: $${stopLoss}`);
      console.log(`  - Recommended Take-Profit: $${takeProfit}`);
      console.log(`  - Current P&L: $${position.unrealizedPnl.toFixed(2)}`);
      
      // Store recommendation in database for manual execution
      const recommendationId = `risk_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      console.log('💾 Storing risk management recommendation...');
      console.log('⚠️ MANUAL ACTION REQUIRED:');
      console.log('   1. Place stop-loss order: LONG 8.86 SOL @ $195.59 (trigger)');
      console.log('   2. Place take-profit order: LONG 8.86 SOL @ $180.68 (limit)');
      console.log('   3. Both orders should have "reduceOnly: true"');
      
    } else {
      console.log('ℹ️ Position is LONG - different risk management logic needed');
    }
    
  } catch (error) {
    console.error('❌ Risk management error:', error.message);
  }
}

// Use node's built-in fetch (Node 18+) or fallback
const fetch = globalThis.fetch || require('node-fetch');

addRiskManagement();
