import { NextResponse } from 'next/server';
import { simpleAutomation } from '@/lib/simple-automation';

export async function POST(request) {
  try {
    const { action, analysis, config } = await request.json();

    if (action === 'generate_test_decision') {
      // Set up test config
      simpleAutomation.config = config || {
        selectedTimeframes: ['15m', '1h', '4h'],
        symbol: 'SOLUSD',
        mode: 'LIVE',
        enableTrading: true,
        tradingAmount: 62
      };

      // Generate decision using the analysis
      const shouldExecute = simpleAutomation.shouldExecuteTrade(analysis);
      
      if (shouldExecute && simpleAutomation.lastDecision) {
        // Add execution details for demo
        simpleAutomation.lastDecision.executed = true;
        simpleAutomation.lastDecision.executionDetails = {
          side: analysis.recommendation?.toLowerCase().includes('buy') ? 'BUY' : 'SELL',
          amount: config.tradingAmount || 62,
          leverage: 12.5,
          currentPrice: analysis.currentPrice || analysis.entry?.price || 186.12,
          stopLoss: analysis.stopLoss,
          takeProfit: analysis.takeProfit,
          aiReasoning: `AI calculated 12.5x leverage based on:
• Stop loss distance: ${((Math.abs(analysis.currentPrice - analysis.stopLoss) / analysis.currentPrice) * 100).toFixed(1)}% (tight risk control)
• Account balance: $${config.tradingAmount || 62} available  
• Safety buffer: 8% (liquidation protection)
• Risk assessment: MODERATE-LOW
• Position value: $${((config.tradingAmount || 62) * 12.5).toFixed(0)} (12.5x leverage)
• Maximum loss if stopped: $${(((Math.abs(analysis.currentPrice - analysis.stopLoss) / analysis.currentPrice) * (config.tradingAmount || 62) * 12.5)).toFixed(0)} (risk controlled)`,
          txId: `test_decision_${Date.now()}`,
          aiStopLossPercent: analysis.stopLossPercent || 'AI calculated'
        };
      }

      return NextResponse.json({
        success: true,
        message: 'Test decision generated',
        decision: simpleAutomation.lastDecision,
        shouldExecute
      });
    }

    return NextResponse.json({
      success: false,
      message: 'Unknown action'
    }, { status: 400 });

  } catch (error) {
    console.error('Test decision error:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to generate test decision',
      message: error.message
    }, { status: 500 });
  }
}
