import type { UserRole } from "@/server/auth/permissions";
import type { users } from "@/server/db/schema";
import type { InferSelectModel } from "drizzle-orm";
import type { RegisteredDatabaseUserAttributes } from "lucia";

// Constants for better readability
export const IS = false;
export const IS_NOT = true;

/**
 * Checks if a user has the required role(s).
 * @param user - The user to check.
 * @param negate - Whether to negate the result.
 * @param roleRequirements - The required role(s).
 * @returns Whether the user has the required role(s).
 */
export function guard(
	user: RegisteredDatabaseUserAttributes | InferSelectModel<typeof users> | undefined | null,
	negate: boolean,
	roleRequirements: UserRole | UserRole[],
) {
	// Early return for unauthenticated users
	if (!user) {
		return true;
	}

	// Normalize roleRequirements to an array
	const requiredRoles = Array.isArray(roleRequirements) ? roleRequirements : [roleRequirements];

	// Check if the user's role is in the required roles
	const userHasRequiredRole = requiredRoles.includes(user.role as UserRole);

	// Return the result, negated if necessary
	return negate ? !userHasRequiredRole : userHasRequiredRole;
}
