import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

import { createInitialSuperAdmin, hasAnySuperAdmin } from '@/lib/services/bootstrap.service';
import { parseBody } from '@/lib/api/route-helpers';
import { ConflictError, errorResponse } from '@/lib/errors';

const bodySchema = z.object({
  name: z.string().min(1).max(120),
  email: z.string().email().max(254),
  password: z.string().min(9).max(200),
});

/**
 * POST /api/v1/bootstrap/super-admin
 *
 * PUBLIC - no auth required, but bound by a single-shot precondition:
 * refuses to run when a super-admin already exists. Idempotently safe:
 * the service double-checks the precondition before insert, so two
 * racing first-run requests can't both create accounts.
 */
export async function POST(req: NextRequest) {
  try {
    // Cheap guard for the common case (someone hits the endpoint by
    // accident after first-run is done). The service repeats this check
    // atomically before the insert.
    if (await hasAnySuperAdmin()) {
      throw new ConflictError(
        'A super-administrator account already exists - first-run setup is closed.',
      );
    }
    const body = await parseBody(req, bodySchema);
    const userId = await createInitialSuperAdmin(body);
    return NextResponse.json({ data: { userId } });
  } catch (error) {
    return errorResponse(error);
  }
}
