import { redirect } from "next/navigation";
import { getSessionUser, type SessionUser } from "@/lib/auth/session";
import { hasAtLeastRole } from "@/lib/roles";
import type { Role } from "@prisma/client";

/**
 * Role-based access control.
 *
 * Every server action and protected page funnels through these guards so that
 * authorization is enforced server-side and never trusted from the client.
 *
 * The role vocabulary itself (ranks, labels) lives in `lib/roles.ts` so Client
 * Components can render it without pulling in `next/headers` and Prisma.
 */

export { ROLE_LABELS, ROLE_ORDER, ROLE_RANK, hasAtLeastRole } from "@/lib/roles";

export class AuthorizationError extends Error {
  constructor(message = "You are not authorized to perform this action.") {
    super(message);
    this.name = "AuthorizationError";
  }
}

/** Redirect unauthenticated visitors to the login page. */
export async function requireUser(callbackUrl?: string): Promise<SessionUser> {
  const user = await getSessionUser();
  if (!user) {
    const target = callbackUrl
      ? `/login?next=${encodeURIComponent(callbackUrl)}`
      : "/login";
    redirect(target);
  }
  return user;
}

export async function requireRole(role: Role, callbackUrl?: string): Promise<SessionUser> {
  const user = await requireUser(callbackUrl);
  if (!hasAtLeastRole(user.role, role)) {
    redirect("/dashboard?error=forbidden");
  }
  return user;
}

export const requireAdmin = (callbackUrl?: string) => requireRole("ADMIN", callbackUrl);
export const requireTeacher = (callbackUrl?: string) => requireRole("TEACHER", callbackUrl);
export const requireStudent = (callbackUrl?: string) => requireRole("STUDENT", callbackUrl);

/**
 * Server-action variant: throws instead of redirecting so callers can return a
 * structured error to the form.
 */
export async function authorize(role: Role): Promise<SessionUser> {
  const user = await getSessionUser();
  if (!user) throw new AuthorizationError("Your session has expired. Please sign in again.");
  if (!hasAtLeastRole(user.role, role)) {
    throw new AuthorizationError("You do not have permission to perform this action.");
  }
  return user;
}

export const authorizeAdmin = () => authorize("ADMIN");
export const authorizeTeacher = () => authorize("TEACHER");
export const authorizeStudent = () => authorize("STUDENT");

/**
 * Ownership checks. Teachers may only mutate resources they own; admins may
 * mutate anything. Returns true when access is granted.
 */
export function canManageOwnedResource(
  actor: Pick<SessionUser, "id" | "role">,
  ownerId: string
): boolean {
  return actor.role === "ADMIN" || actor.id === ownerId;
}
