from rest_framework.permissions import IsAuthenticated, SAFE_METHODS


class CanEditHub(IsAuthenticated):
    """
    Hub object-level permission.
    - View-level: must be authenticated (inherited).
    - Object-level unsafe: hub owner, superuser, or any moderator
      (field-level restrictions enforced in HubSerializer).
    """

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        
        user = request.user
        if obj.owner == user or user.is_superuser:
            return True
        
        return obj.moderators.filter(user=user).exists()


class IsHubOwnerOrSuperuser(IsAuthenticated):
    """
    For objects with a .hub FK (e.g. HubPermission).
    - View-level: must be authenticated (inherited).
    - Object-level unsafe: hub owner or superuser only.
    """

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        
        return request.user.is_superuser or obj.hub.owner == request.user


class CanManageHubTags(IsAuthenticated):
    """
    For Tags (navigates via obj.hub).
    - View-level: must be authenticated (inherited).
    - Object-level unsafe: hub owner, superuser, or moderator with managing_posts=True.
    """

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        
        user = request.user
        hub = obj.hub
        if user.is_superuser or hub.owner == user:
            return True
        
        return hub.moderators.filter(user=user, managing_posts=True).exists()
