import { NextResponse } from 'next/server';

export async function POST(request) {
  try {
    const body = await request.json();
    const { dryRun = true, analysis = null } = body;
    
    console.log('🧹 CONSOLIDATING POSITION ORDERS');
    console.log(`Mode: ${dryRun ? 'DRY RUN' : 'LIVE EXECUTION'}`);
    console.log(`AI Analysis: ${analysis ? 'Provided - Using AI optimal levels' : 'Not provided - Using adaptive levels'}`);
    
    // Get current position data
    const positionsResponse = await fetch('http://localhost:3000/api/drift/positions');
    const positionsData = await positionsResponse.json();
    
    if (!positionsData.success || !positionsData.positions.length) {
      return NextResponse.json({
        success: false,
        error: 'No active positions found to consolidate'
      }, { status: 400 });
    }
    
    const position = positionsData.positions[0]; // Get first position
    
    // Import the consolidator
    const PositionConsolidator = await import('../../../../lib/position-consolidator.js');
    
    if (dryRun) {
      // Dry run: analyze only with AI analysis if provided
      const consolidatedPlan = await PositionConsolidator.default.analyzeAndConsolidate(analysis);
      
      return NextResponse.json({
        success: true,
        mode: 'dry_run',
        plan: consolidatedPlan,
        message: analysis ? 'AI-optimized consolidation plan ready' : 'Adaptive consolidation plan ready',
        position: {
          symbol: position.symbol,
          side: position.side,
          size: position.size,
          entryPrice: position.entryPrice
        }
      });
      
    } else {
      // Live execution with AI analysis if provided
      const consolidationResult = await PositionConsolidator.default.executeConsolidation(analysis);
      
      if (consolidationResult.success) {
        return NextResponse.json({
          success: true,
          message: analysis ? 'Position consolidated using AI optimal levels' : 'Position consolidated using adaptive levels',
          consolidation: {
            ordersBefore: consolidationResult.ordersBefore,
            ordersAfter: consolidationResult.ordersAfter,
            position: {
              symbol: position.symbol,
              side: position.side,
              size: position.size,
              entryPrice: position.entryPrice
            }
          },
          orders: consolidationResult.results
        });
      } else {
        return NextResponse.json({
          success: false,
          error: consolidationResult.error
        }, { status: 500 });
      }
    }
    
  } catch (error) {
    console.error('❌ Position consolidation error:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to consolidate position',
      details: error.message
    }, { status: 500 });
  }
}
