from typing import Literal

from django_redis import get_redis_connection
from redis.client import Redis


def generate_perm_cache_key(user_id: str):
    return f"user:{user_id}:permissions"


def has_perm(user_id, perm):
    redis_conn: Redis = get_redis_connection("shared")

    return bool(redis_conn.sismember(f'user:{user_id}:permissions', perm))


def has_perms(user_id: str, perms: list[str], operator: Literal["OR", "AND"] = "OR"):
    redis_conn: Redis = get_redis_connection("shared")

    result = redis_conn.smismember(f'user:{user_id}:permissions', perms)

    if operator == "OR":
        return any(result)
    return all(result)
