from functools import wraps

from django.core.exceptions import PermissionDenied


ADMIN = "Admin"
OPERATOR = "Operator"
DISPATCHER = "Dispatcher"


def role_required(*allowed_roles):
    """
    Restrict a view to active staff users in one of the named Django Groups.
    Superusers are allowed through. Assign users to Groups in Django Admin.
    """
    def decorator(view_func):
        @wraps(view_func)
        def wrapped(request, *args, **kwargs):
            user = request.user
            if not user.is_authenticated or not user.is_active or not user.is_staff:
                raise PermissionDenied("Staff access is required.")

            if user.is_superuser:
                return view_func(request, *args, **kwargs)

            if not user.groups.filter(name__in=allowed_roles).exists():
                raise PermissionDenied("Your staff role does not permit this action.")

            return view_func(request, *args, **kwargs)
        return wrapped
    return decorator
