from functools import wraps
from typing import Literal

from rest_framework.exceptions import PermissionDenied

from .utils import has_perms as has_permissions


def has_perm(*permission: str, operator: Literal["OR", "AND"] = "OR"):
    """
    Usage:
        has_perm('PERM1')
        has_perm('PERM1', 'PERM2')

    :param permission: One or many permissions.
    """
    def decorator(view_func):
        view_func._perms = permission
        @wraps(view_func)
        def _wrapped_view(self, request, *args, **kwargs):
            if not has_permissions(user_id=request.user.id, perms=list(permission), operator=operator):
                raise PermissionDenied
            return view_func(self, request, *args, **kwargs)
        return _wrapped_view
    return decorator
