"""
ViewSet for Notification Log API.
"""

from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import viewsets
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.permissions import IsAdminUser

from apps.notifications.models import NotificationLog

from .log_serializers import NotificationLogSerializer


@extend_schema_view(
    list=extend_schema(
        summary="List notification logs",
        description="Get all notification logs with optional filtering by status, channel, or workflow.",
        tags=["Admin - Notifications"],
    ),
    retrieve=extend_schema(
        summary="Get notification log",
        description="Get details of a specific notification log entry.",
        tags=["Admin - Notifications"],
    ),
)
class NotificationLogViewSet(viewsets.ReadOnlyModelViewSet):
    """
    ViewSet for viewing notification logs.

    Provides read-only access to notification delivery history.
    """

    queryset = NotificationLog.objects.select_related("user").all()
    serializer_class = NotificationLogSerializer
    permission_classes = [IsAdminUser]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ["status", "channel", "workflow_id", "notification_type"]
    search_fields = ["workflow_id", "notification_type", "error_message"]
    ordering_fields = ["created_at", "status"]
    ordering = ["-created_at"]

    def get_queryset(self):
        queryset = super().get_queryset()

        # Filter by user ID if provided
        user_id = self.request.query_params.get("user_id")
        if user_id:
            queryset = queryset.filter(user_id=user_id)

        # Date range filtering
        start_date = self.request.query_params.get("start_date")
        end_date = self.request.query_params.get("end_date")

        if start_date:
            queryset = queryset.filter(created_at__gte=start_date)
        if end_date:
            queryset = queryset.filter(created_at__lte=end_date)

        return queryset
