import { NextRequest, NextResponse } from 'next/server';
import { completeSetupRun } 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 {
      setupRunId?: string;
      report?: Record<string, unknown>;
    };

    return NextResponse.json(
      await completeSetupRun({
        actorId: session.user.id,
        setupRunId: body.setupRunId,
        report: body.report
      })
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

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