"use server";

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { revalidatePath } from "next/cache";

type Result = { ok: true } | { error: string };

export async function resolveRequest(
  requestId: string,
  decision: "APPROVED" | "DENIED"
): Promise<Result> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_users")) {
    return { error: "Unauthorized" };
  }

  const request = await db.superUserRequest.findUnique({
    where: { id: requestId },
    include: { user: true },
  });
  if (!request) return { error: "Request not found" };
  if (request.status !== "PENDING") return { error: "Request has already been resolved" };

  await db.$transaction(async (tx) => {
    await tx.superUserRequest.update({
      where: { id: requestId },
      data: {
        status: decision,
        resolvedAt: new Date(),
        resolvedById: session.user.id,
      },
    });

    if (decision === "APPROVED") {
      await tx.user.update({
        where: { id: request.userId },
        data: { role: "SUPERUSER" },
      });
    }
  });

  revalidatePath("/admin/superuser-requests");
  revalidatePath("/admin/users");
  return { ok: true };
}

export async function grantSuperUser(userId: string): Promise<Result> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_users")) {
    return { error: "Unauthorized" };
  }

  const user = await db.user.findUnique({ where: { id: userId }, select: { role: true, name: true } });
  if (!user) return { error: "User not found" };
  if (user.role === "SUPERUSER") return { error: "User is already a SuperUser" };
  if (user.role === "ADMIN") return { error: "Cannot change Admin role" };

  await db.user.update({ where: { id: userId }, data: { role: "SUPERUSER" } });

  // Auto-close any pending request for this user
  await db.superUserRequest.updateMany({
    where: { userId, status: "PENDING" },
    data: { status: "APPROVED", resolvedAt: new Date(), resolvedById: session.user.id },
  });

  revalidatePath("/admin/users");
  revalidatePath("/admin/superuser-requests");
  return { ok: true };
}
