import { NextResponse } from "next/server";

import { requireSuperAdmin } from "@/lib/authorization";
import {
  getAuthUserById,
  replaceAuthUserPermissions,
} from "@/services/auth-users.service";
import { authUserPermissionsUpdateSchema } from "@/validators/auth-users";

type RouteContext = {
  params: Promise<{ id: string }>;
};

function parseId(value: string) {
  const id = Number(value);
  return Number.isInteger(id) && id > 0 ? id : null;
}

export async function PATCH(request: Request, { params }: RouteContext) {
  const auth = await requireSuperAdmin(request);

  if (!auth.ok) return auth.response;

  const { id: rawId } = await params;
  const id = parseId(rawId);

  if (id == null) {
    return NextResponse.json(
      { message: "Identifiant utilisateur invalide" },
      { status: 400 },
    );
  }

  let body: unknown;

  try {
    body = await request.json();
  } catch {
    return NextResponse.json(
      { message: "Corps JSON invalide" },
      { status: 400 },
    );
  }

  const parsed = authUserPermissionsUpdateSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json(
      {
        message: "Habilitations invalides",
        errors: parsed.error.flatten(),
      },
      { status: 400 },
    );
  }

  const target = await getAuthUserById(id);

  if (!target) {
    return NextResponse.json(
      { message: "Utilisateur introuvable" },
      { status: 404 },
    );
  }

  if (target.role === "super_admin") {
    return NextResponse.json(
      { message: "Le super-administrateur est protégé" },
      { status: 403 },
    );
  }

  try {
    const user = await replaceAuthUserPermissions(id, parsed.data);

    return NextResponse.json({
      message: `Les habilitations de ${target.email ?? target.username} ont été enregistrées.`,
      item: user,
    });
  } catch (error) {
    const code = error instanceof Error ? error.message : "";

    if (code === "UNKNOWN_SECTOR") {
      return NextResponse.json(
        { message: "Au moins un secteur sélectionné n'existe plus" },
        { status: 400 },
      );
    }

    if (code === "UNKNOWN_ESTABLISHMENT") {
      return NextResponse.json(
        { message: "Au moins un établissement sélectionné n'existe plus" },
        { status: 400 },
      );
    }

    if (code === "UNKNOWN_CATEGORY") {
      return NextResponse.json(
        { message: "Au moins une catégorie sélectionnée n'existe plus" },
        { status: 400 },
      );
    }

    if (code === "UNKNOWN_CONTRACT_TYPE") {
      return NextResponse.json(
        { message: "Au moins un type de contrat sélectionné n'existe plus" },
        { status: 400 },
      );
    }

    if (code === "SUPER_ADMIN_PROTECTED") {
      return NextResponse.json(
        { message: "Le super-administrateur est protégé" },
        { status: 403 },
      );
    }

    throw error;
  }
}
