import { NextRequest, NextResponse } from 'next/server';
import { startSetupRun } from '@/features/setup/server/setup-state.service';
import { AuthError, requireSystemRole } from '@/lib/auth/session';

export async function POST(request: NextRequest) {
  try {
    const session = await requireSystemRole('super_admin');
    const body = (await request.json().catch(() => ({}))) as {
      mode?: 'production' | 'demo_uat' | 'dry_run';
      targetOrganizationId?: string | null;
    };

    return NextResponse.json(
      await startSetupRun({
        actorId: session.user.id,
        mode: body.mode,
        targetOrganizationId: body.targetOrganizationId ?? null
      })
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to start setup run' }, { status: 500 });
  }
}
