from rest_framework import generics, filters
from rest_framework.permissions import AllowAny
from django_filters.rest_framework import DjangoFilterBackend

from .models import Article, Category
from .permissions import is_eligible_for_adherent_content
from .serializers import (
    ArticleListSerializer,
    ArticleDetailSerializer,
    CategorySerializer,
)


class AdherentEligibilityContextMixin:
    """
    Injecte `is_eligible` dans le contexte du serializer pour permettre
    le gating du contenu réservé aux adhérents.
    """

    def get_serializer_context(self):
        ctx = super().get_serializer_context()
        ctx['is_eligible'] = is_eligible_for_adherent_content(self.request)
        return ctx


class ArticleListView(AdherentEligibilityContextMixin, generics.ListAPIView):
    """
    GET /api/blog/articles/
    List published articles with optional filtering.

    Query params:
        - lang: 'fr' or 'ar' (default: 'fr') — language for localized fields
        - category: filter by category slug
        - search: search in title and excerpt
        - ordering: order by published_date, created_at (default: -published_date)
    """
    serializer_class = ArticleListSerializer
    permission_classes = [AllowAny]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = {'category__slug': ['exact']}
    search_fields = ['translations__title', 'translations__excerpt']
    ordering_fields = ['published_date', 'created_at']
    ordering = ['-published_date']

    def get_queryset(self):
        return (
            Article.objects
            .filter(status='published')
            .select_related('category', 'author')
            .prefetch_related('translations', 'category__translations')
            .order_by('-published_date')
        )


class ArticleDetailView(AdherentEligibilityContextMixin, generics.RetrieveAPIView):
    """
    GET /api/blog/articles/<slug>/
    Retrieve a single published article by slug.

    Query params:
        - lang: 'fr' or 'ar' (default: 'fr')
    """
    serializer_class = ArticleDetailSerializer
    permission_classes = [AllowAny]
    lookup_field = 'slug'

    def get_queryset(self):
        return (
            Article.objects
            .filter(status='published')
            .select_related('category', 'author')
            .prefetch_related('translations', 'category__translations')
        )


class CategoryListView(generics.ListAPIView):
    """
    GET /api/blog/categories/
    List all categories.

    Query params:
        - lang: 'fr' or 'ar' (default: 'fr')
    """
    serializer_class = CategorySerializer
    permission_classes = [AllowAny]

    def get_queryset(self):
        return (
            Category.objects
            .prefetch_related('translations')
            .order_by('slug')
        )


class PinnedArticlesView(AdherentEligibilityContextMixin, generics.ListAPIView):
    """
    GET /api/blog/pinned/
    List pinned published articles.

    Query params:
        - lang: 'fr' or 'ar' (default: 'fr')
    """
    serializer_class = ArticleListSerializer
    permission_classes = [AllowAny]

    def get_queryset(self):
        return (
            Article.objects
            .filter(status='published', pined_article=True)
            .select_related('category', 'author')
            .prefetch_related('translations', 'category__translations')
            .order_by('-published_date')
        )
