from functools import wraps
from django.http import JsonResponse
from org_authz.models import UserRole, RolePermission


def org_permission_required(permission_code):
    """
    Decorator to protect views easily.
    Example:
        @org_permission_required("can_add_invoice")
        def create_invoice(request):
            ...
    """
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            user_roles = UserRole.objects.filter(user=request.user)
            role_ids = [ur.role_id for ur in user_roles]

            has_permission = RolePermission.objects.filter(
                role_id__in=role_ids,
                permission__code=permission_code,
            ).exists()

            if not has_permission:
                return JsonResponse({"detail": "Permission denied"}, status=403)
            return view_func(request, *args, **kwargs)

        return wrapper
    return decorator
