import { NextRequest, NextResponse } from 'next/server';
import { requireAdmin } from '@/lib/auth-server';
import { restartServiceContainer } from '@/lib/docker-control';

export const dynamic = 'force-dynamic';

export async function POST(req: NextRequest) {
  try {
    const admin = await requireAdmin(req);
    if (!admin) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const body = await req.json().catch(() => null);
    if (!body || body.action !== 'restart' || typeof body.serviceId !== 'string') {
      return NextResponse.json({ error: 'Invalid control request' }, { status: 400 });
    }

    const result = await restartServiceContainer(body.serviceId);
    return NextResponse.json({
      ok: true,
      action: 'restart',
      serviceId: body.serviceId,
      container: result.container,
      requestedAt: new Date().toISOString(),
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Control action failed';
    const status = message === 'Unauthorized' ? 401 : 500;
    return NextResponse.json({ error: message }, { status });
  }
}
