"""
Park history API views.
"""

from django.shortcuts import get_object_or_404
from drf_spectacular.utils import extend_schema
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from apps.api.v1.serializers.history import ParkHistoryOutputSerializer, RideHistoryOutputSerializer
from apps.parks.models import Park
from apps.rides.models import Ride


class ParkHistoryViewSet(viewsets.GenericViewSet):
    """
    ViewSet for retrieving park history.
    """

    permission_classes = [AllowAny]
    lookup_field = "slug"
    lookup_url_kwarg = "park_slug"

    @extend_schema(
        summary="Get park history",
        description="Retrieve history events for a park.",
        responses={200: ParkHistoryOutputSerializer},
        tags=["Park History"],
    )
    def list(self, request, park_slug=None):
        park = get_object_or_404(Park, slug=park_slug)

        events = []
        if hasattr(park, "events"):
            events = park.events.all().order_by("-pgh_created_at")

        summary = {
            "total_events": len(events),
            "first_recorded": events.last().pgh_created_at if len(events) else None,
            "last_modified": events.first().pgh_created_at if len(events) else None,
        }

        data = {"park": park, "current_state": park, "summary": summary, "events": events}

        serializer = ParkHistoryOutputSerializer(data)
        return Response(serializer.data)


class RideHistoryViewSet(viewsets.GenericViewSet):
    """
    ViewSet for retrieving ride history.
    """

    permission_classes = [AllowAny]
    lookup_field = "slug"
    lookup_url_kwarg = "ride_slug"

    @extend_schema(
        summary="Get ride history",
        description="Retrieve history events for a ride.",
        responses={200: RideHistoryOutputSerializer},
        tags=["Ride History"],
    )
    def list(self, request, park_slug=None, ride_slug=None):
        park = get_object_or_404(Park, slug=park_slug)
        ride = get_object_or_404(Ride, slug=ride_slug, park=park)

        events = []
        if hasattr(ride, "events"):
            events = ride.events.all().order_by("-pgh_created_at")

        summary = {
            "total_events": len(events),
            "first_recorded": events.last().pgh_created_at if len(events) else None,
            "last_modified": events.first().pgh_created_at if len(events) else None,
        }

        data = {"ride": ride, "current_state": ride, "summary": summary, "events": events}

        serializer = RideHistoryOutputSerializer(data)
        return Response(serializer.data)
