"""
Milestone views for timeline events.
"""

from django_filters import rest_framework as filters
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.response import Response

from apps.core.models import Milestone

from .milestone_serializers import (
    MilestoneCreateSerializer,
    MilestoneListSerializer,
    MilestoneSerializer,
)


class MilestoneFilter(filters.FilterSet):
    """Filters for milestone listing."""

    entity_type = filters.CharFilter(field_name="entity_type")
    entity_id = filters.UUIDFilter(field_name="entity_id")
    event_type = filters.CharFilter(field_name="event_type")
    is_public = filters.BooleanFilter(field_name="is_public")
    event_date_after = filters.DateFilter(field_name="event_date", lookup_expr="gte")
    event_date_before = filters.DateFilter(field_name="event_date", lookup_expr="lte")

    class Meta:
        model = Milestone
        fields = ["entity_type", "entity_id", "event_type", "is_public"]


class MilestoneViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing milestones/timeline events.

    Supports filtering by entity_type, entity_id, event_type, and date range.
    """

    queryset = Milestone.objects.all()
    filterset_class = MilestoneFilter
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get_serializer_class(self):
        if self.action == "list":
            return MilestoneListSerializer
        if self.action == "create":
            return MilestoneCreateSerializer
        return MilestoneSerializer

    def get_queryset(self):
        """Filter queryset based on visibility."""
        queryset = super().get_queryset()

        # Non-authenticated users only see public milestones
        if not self.request.user.is_authenticated:
            queryset = queryset.filter(is_public=True)

        return queryset.order_by("-event_date", "display_order")

    @action(detail=False, methods=["get"], url_path="entity/(?P<entity_type>[^/]+)/(?P<entity_id>[^/]+)")
    def by_entity(self, request, entity_type=None, entity_id=None):
        """Get all milestones for a specific entity."""
        queryset = self.get_queryset().filter(
            entity_type=entity_type,
            entity_id=entity_id,
        )
        serializer = MilestoneListSerializer(queryset, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=["get"], url_path="timeline")
    def timeline(self, request):
        """Get a unified timeline view of recent milestones across all entities."""
        limit = int(request.query_params.get("limit", 50))
        queryset = self.get_queryset()[:limit]
        serializer = MilestoneListSerializer(queryset, many=True)
        return Response(serializer.data)
