import { NextResponse } from 'next/server';
import { exec } from 'child_process';
import util from 'util';

const execPromise = util.promisify(exec);

export async function POST(_req: Request) {
  try {
    // Ideally we should verify JWT role: admin here, but for demonstration of the architecture:
    
    // Command to scale up by 1 instance
    const { stdout, stderr } = await execPromise('pm2 scale jumpa-chat +1');
    
    console.log('[CLUSTER SCALE] stdout:', stdout);
    if (stderr) console.error('[CLUSTER SCALE] stderr:', stderr);

    // Give it 1 second to warm up
    await new Promise(resolve => setTimeout(resolve, 1000));

    return NextResponse.json({ success: true, message: 'Node scaled successfully', stdout }, { status: 200 });

  } catch (error) {
    console.error('[CLUSTER SCALE ERROR]', error);
    return NextResponse.json({ error: 'Failed to scale cluster' }, { status: 500 });
  }
}
