from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, permissions, viewsets

from apps.core.permissions import IsOwnerOrReadOnly

from .models import Review
from .serializers import ReviewSerializer


class ReviewViewSet(viewsets.ModelViewSet):
    queryset = Review.objects.filter(is_public=True)
    serializer_class = ReviewSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ["content_type", "object_id", "rating", "user"]
    ordering_fields = ["created_at", "rating", "helpful_votes"]
    ordering = ["-created_at"]

    def get_queryset(self):
        # Users can see their own non-public reviews?
        # Standard queryset is public only.
        # But if we want authors to see their own pending/private reviews:
        qs = Review.objects.filter(is_public=True)
        if self.request.user.is_authenticated:
            # Add user's own reviews even if not public (if that's a use case)
            qs = qs | Review.objects.filter(user=self.request.user)
        return qs.distinct()

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
