from rest_framework.permissions import IsAuthenticated, SAFE_METHODS


class IsChatMember(IsAuthenticated):
    """
    View-level: must be authenticated (inherited).
    Object-level: safe methods require chat membership; unsafe require membership too.
    Used for reading messages and listing chat details.
    """

    def has_object_permission(self, request, view, obj):
        return (
            request.user.is_superuser
            or obj.owner == request.user
            or obj.members.filter(pk=request.user.pk).exists()
        )


class CanManageChat(IsAuthenticated):
    """
    View-level: must be authenticated (inherited).
    Object-level unsafe: chat owner, moderator, or superuser.
    Used for editing/deleting the chat itself and managing members.
    """

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


class IsMessageSenderOnly(IsAuthenticated):
    """
    View-level: must be authenticated (inherited).
    Object-level unsafe: message sender only.
    Used for editing messages.
    """

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


class CanDeleteMessage(IsAuthenticated):
    """
    View-level: must be authenticated (inherited).
    Object-level DELETE:
      - Message sender
      - Superuser
      - Chat owner
      - Chat moderator
    """

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