import { NextResponse } from "next/server";

import { requireSuperAdmin } from "@/lib/authorization";
import { normalizeAppRole } from "@/lib/roles";
import {
  getAuthUserById,
  updateAuthUserById,
} from "@/services/auth-users.service";
import { authUserUpdateSchema } 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: "Invalid user ID" }, { status: 400 });
  }

  if (id === auth.principal.id) {
    return NextResponse.json(
      {
        message: "You cannot modify your own role or account status",
      },
      { status: 409 },
    );
  }

  let body: unknown;

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

  const parsed = authUserUpdateSchema.safeParse(body);

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

  const target = await getAuthUserById(id);

  if (!target) {
    return NextResponse.json({ message: "User not found" }, { status: 404 });
  }

  const targetRole = normalizeAppRole(target.role);

  if (targetRole === "super_admin") {
    return NextResponse.json(
      {
        message: "Super administrator accounts can only be modified manually",
      },
      { status: 403 },
    );
  }

  const user = await updateAuthUserById(id, parsed.data);

  return NextResponse.json({
    message: "User updated successfully",
    item: user,
  });
}
