import { NextResponse } from "next/server";
import { UserRole } from "@prisma/client";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { buildAppUrl } from "@/lib/http/url";

function redirectTo(request: Request, status: string) {
  return NextResponse.redirect(buildAppUrl(request, "/admin", { status }));
}

export async function POST(request: Request) {
  const adminUser = await requireAdminApiUser();

  if (!adminUser) {
    return redirectTo(request, "admin_error");
  }

  const formData = await request.formData();
  const userId = typeof formData.get("userId") === "string" ? formData.get("userId")!.toString() : "";
  const roleValue = typeof formData.get("role") === "string" ? formData.get("role")!.toString() : "";

  if (!userId || (roleValue !== UserRole.USER && roleValue !== UserRole.ADMIN)) {
    return redirectTo(request, "admin_error");
  }

  try {
    await prisma.user.update({
      where: { id: userId },
      data: {
        role: roleValue as UserRole,
      },
    });

    return redirectTo(request, "role_updated");
  } catch {
    return redirectTo(request, "admin_error");
  }
}
