from rest_framework.permissions import IsAuthenticated, SAFE_METHODS


class IsPostAuthorOnly(IsAuthenticated):
    """
    View-level: must be authenticated (inherited).
    Object-level unsafe: post author only.
    Used for update / partial_update.
    """

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        
        return obj.author == request.user


class CanDeletePost(IsAuthenticated):
    """
    View-level: must be authenticated (inherited).
    Object-level DELETE:
      - Post author
      - Superuser (anywhere)
      - Hub owner (if post belongs to a hub)
      - Hub moderator with managing_posts=True (if post belongs to a hub)
    """

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