from django.utils import timezone
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, permissions, viewsets

from apps.core.permissions import IsStaffOrReadOnly

from .models import Post, Tag
from .serializers import PostDetailSerializer, PostListSerializer, TagSerializer


class TagViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    permission_classes = [permissions.AllowAny]
    filter_backends = [filters.SearchFilter]
    search_fields = ["name"]
    pagination_class = None  # Tags are usually few


class PostViewSet(viewsets.ModelViewSet):
    """
    Public API: Read Only (unless staff).
    Only published posts unless staff.
    """

    permission_classes = [IsStaffOrReadOnly]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    search_fields = ["title", "excerpt", "content"]
    filterset_fields = ["tags__slug", "is_published"]
    ordering_fields = ["published_at", "created_at"]
    ordering = ["-published_at"]
    lookup_field = "slug"

    def get_queryset(self):
        qs = Post.objects.all()
        # If not staff, filter only published and past posts
        if not self.request.user.is_staff:
            qs = qs.filter(is_published=True, published_at__lte=timezone.now())
        return qs.select_related("author", "image").prefetch_related("tags")

    def get_serializer_class(self):
        if self.action == "list":
            return PostListSerializer
        return PostDetailSerializer

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