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

from apps.core.permissions import IsOwnerOrReadOnly

from .models import Photo
from .serializers import PhotoSerializer


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

    def get_queryset(self):
        qs = Photo.objects.filter(is_public=True)
        if self.request.user.is_authenticated:
            qs = qs | Photo.objects.filter(user=self.request.user)
        return qs.distinct()

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