import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getSetupVerificationReport } from '@/features/setup/server/verification.service';
import { AuthError, requireSystemRole } from '@/lib/auth/session';

const verificationSchema = z
  .object({
    organizationId: z.string().min(1).optional(),
    administratorEmail: z.string().email().optional(),
    profileId: z.string().min(1).optional()
  })
  .optional();

export async function POST(request: NextRequest) {
  try {
    const session = await requireSystemRole('super_admin');
    const body = verificationSchema.parse(await request.json().catch(() => undefined)) ?? {};
    const report = await getSetupVerificationReport({
      organizationId: body.organizationId ?? session.user.activeOrganizationId ?? null,
      administratorEmail: body.administratorEmail,
      profileId: body.profileId
    });

    return NextResponse.json(report);
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: 'Invalid setup verification payload', errors: error.flatten() },
        { status: 400 }
      );
    }

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