import "server-only";

import { redirect } from "next/navigation";

import { ActionError } from "@/lib/actions";
import { getSession, type CurrentAdmin } from "@/lib/auth/session";

export type AdminRole = CurrentAdmin["role"];

export async function getCurrentAdmin() {
  return (await getSession())?.user ?? null;
}

/**
 * For Server Components: the signed-in admin, or a redirect to the login page.
 * Proxy only checks that a cookie exists; this validates it.
 */
export async function requireAdmin(role?: AdminRole) {
  const admin = await getCurrentAdmin();
  if (!admin) redirect("/login");
  if (role && !hasRole(admin, role)) redirect("/admin");
  return admin;
}

/**
 * For Server Actions and Route Handlers. Every mutation calls this itself:
 * a page-level check does not protect the actions defined on that page.
 */
export async function requireActionAdmin(role?: AdminRole) {
  const admin = await getCurrentAdmin();
  if (!admin) {
    throw new ActionError("Your session has expired. Sign in again.", 401);
  }
  if (role && !hasRole(admin, role)) {
    throw new ActionError("You don't have permission to do that.", 403);
  }
  return admin;
}

export function hasRole(admin: Pick<CurrentAdmin, "role">, role: AdminRole) {
  return role === "EDITOR" || admin.role === "ADMIN";
}
