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";

// Helpers to improve readability of the guard function
export const is = false;
export const is_not = true;

/**
 * @deprecated
 */
export function guard(
	user: RegisteredDatabaseUserAttributes | InferSelectModel<typeof users> | undefined | null,
	negate: boolean,
	roleRequirements: UserRole | UserRole[],
) {
	if (!user) {
		return true; // Guard against unauthenticated users
	}

	const hasRole = Array.isArray(roleRequirements)
		? roleRequirements.includes(user?.role as UserRole)
		: user?.role === roleRequirements;

	return negate ? !hasRole : hasRole;
}

export class PermissionError extends Error {
	constructor() {
		super("Du besitzt nicht die erforderlichen Berechtigungen um diese Aktion auszuführen.");
	}
}
