import { EntityWithRoles } from "@/interfaces/entity";
import { User } from "@/interfaces/user";
import { RolePermission } from "@/resources/entityPermissions";
import { mapBy } from "@/utils";
import { doesEntityAllow, findAllowedEntities, findAllowedEntitiesSomePermissions } from "@/utils/permissions";
import { isAdmin } from "@/utils/users";
import { useMemo, useState } from "react";

export const useAllowedEntities = (user: User, entities: EntityWithRoles[], permission: RolePermission) => {
	const allowedEntityIds = useMemo(() => findAllowedEntities(user, entities, permission), [user, entities, permission])
	return allowedEntityIds
}

export const useAllowedEntitiesSomePermissions = (user: User, entities: EntityWithRoles[], permissions: RolePermission[]) => {
	const allowedEntityIds = useMemo(() => findAllowedEntitiesSomePermissions(user, entities, permissions), [user, entities, permissions])
	return allowedEntityIds
}

export const useEntityPermission = (user: User, entity?: EntityWithRoles, permission?: RolePermission) => {
	if (isAdmin(user)) return true
	if (!entity || !permission) return false

	return doesEntityAllow(user, entity, permission)
}
