"""
ViewSets for admin alert API endpoints.

Provides CRUD operations for SystemAlert, RateLimitAlert, and RateLimitAlertConfig.
"""

from django.utils import timezone
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response

from apps.core.models import RateLimitAlert, RateLimitAlertConfig, SystemAlert

from .alert_serializers import (
    RateLimitAlertConfigSerializer,
    RateLimitAlertResolveSerializer,
    RateLimitAlertSerializer,
    SystemAlertResolveSerializer,
    SystemAlertSerializer,
)


@extend_schema_view(
    list=extend_schema(
        summary="List system alerts",
        description="Get all system alerts, optionally filtered by severity or resolved status.",
        tags=["Admin - Alerts"],
    ),
    retrieve=extend_schema(
        summary="Get system alert",
        description="Get details of a specific system alert.",
        tags=["Admin - Alerts"],
    ),
    create=extend_schema(
        summary="Create system alert",
        description="Create a new system alert.",
        tags=["Admin - Alerts"],
    ),
    update=extend_schema(
        summary="Update system alert",
        description="Update an existing system alert.",
        tags=["Admin - Alerts"],
    ),
    partial_update=extend_schema(
        summary="Partial update system alert",
        description="Partially update an existing system alert.",
        tags=["Admin - Alerts"],
    ),
    destroy=extend_schema(
        summary="Delete system alert",
        description="Delete a system alert.",
        tags=["Admin - Alerts"],
    ),
)
class SystemAlertViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing system alerts.

    Provides CRUD operations plus a resolve action for marking alerts as resolved.
    """

    queryset = SystemAlert.objects.all()
    serializer_class = SystemAlertSerializer
    permission_classes = [IsAdminUser]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ["severity", "alert_type"]
    search_fields = ["message"]
    ordering_fields = ["created_at", "severity"]
    ordering = ["-created_at"]

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

        # Filter by resolved status
        resolved = self.request.query_params.get("resolved")
        if resolved is not None:
            if resolved.lower() == "true":
                queryset = queryset.exclude(resolved_at__isnull=True)
            elif resolved.lower() == "false":
                queryset = queryset.filter(resolved_at__isnull=True)

        return queryset

    @extend_schema(
        summary="Resolve system alert",
        description="Mark a system alert as resolved.",
        request=SystemAlertResolveSerializer,
        responses={200: SystemAlertSerializer},
        tags=["Admin - Alerts"],
    )
    @action(detail=True, methods=["post"])
    def resolve(self, request, pk=None):
        """Mark an alert as resolved."""
        alert = self.get_object()

        if alert.resolved_at:
            return Response(
                {"detail": "Alert is already resolved"},
                status=status.HTTP_400_BAD_REQUEST,
            )

        alert.resolved_at = timezone.now()
        alert.resolved_by = request.user
        alert.save()

        serializer = self.get_serializer(alert)
        return Response(serializer.data)


@extend_schema_view(
    list=extend_schema(
        summary="List rate limit alert configs",
        description="Get all rate limit alert configurations.",
        tags=["Admin - Alerts"],
    ),
    retrieve=extend_schema(
        summary="Get rate limit alert config",
        description="Get details of a specific rate limit alert configuration.",
        tags=["Admin - Alerts"],
    ),
    create=extend_schema(
        summary="Create rate limit alert config",
        description="Create a new rate limit alert configuration.",
        tags=["Admin - Alerts"],
    ),
    update=extend_schema(
        summary="Update rate limit alert config",
        description="Update an existing rate limit alert configuration.",
        tags=["Admin - Alerts"],
    ),
    partial_update=extend_schema(
        summary="Partial update rate limit alert config",
        description="Partially update an existing rate limit alert configuration.",
        tags=["Admin - Alerts"],
    ),
    destroy=extend_schema(
        summary="Delete rate limit alert config",
        description="Delete a rate limit alert configuration.",
        tags=["Admin - Alerts"],
    ),
)
class RateLimitAlertConfigViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing rate limit alert configurations.

    Provides CRUD operations for alert thresholds.
    """

    queryset = RateLimitAlertConfig.objects.all()
    serializer_class = RateLimitAlertConfigSerializer
    permission_classes = [IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = ["metric_type", "enabled"]
    ordering_fields = ["created_at", "metric_type", "threshold_value"]
    ordering = ["metric_type", "-created_at"]


@extend_schema_view(
    list=extend_schema(
        summary="List rate limit alerts",
        description="Get all rate limit alerts, optionally filtered by resolved status.",
        tags=["Admin - Alerts"],
    ),
    retrieve=extend_schema(
        summary="Get rate limit alert",
        description="Get details of a specific rate limit alert.",
        tags=["Admin - Alerts"],
    ),
)
class RateLimitAlertViewSet(viewsets.ReadOnlyModelViewSet):
    """
    ViewSet for viewing rate limit alerts.

    Provides read-only access and a resolve action.
    """

    queryset = RateLimitAlert.objects.select_related("config").all()
    serializer_class = RateLimitAlertSerializer
    permission_classes = [IsAdminUser]
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ["metric_type"]
    search_fields = ["alert_message", "function_name"]
    ordering_fields = ["created_at", "metric_value"]
    ordering = ["-created_at"]

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

        # Filter by resolved status
        resolved = self.request.query_params.get("resolved")
        if resolved is not None:
            if resolved.lower() == "true":
                queryset = queryset.exclude(resolved_at__isnull=True)
            elif resolved.lower() == "false":
                queryset = queryset.filter(resolved_at__isnull=True)

        return queryset

    @extend_schema(
        summary="Resolve rate limit alert",
        description="Mark a rate limit alert as resolved.",
        request=RateLimitAlertResolveSerializer,
        responses={200: RateLimitAlertSerializer},
        tags=["Admin - Alerts"],
    )
    @action(detail=True, methods=["post"])
    def resolve(self, request, pk=None):
        """Mark an alert as resolved."""
        alert = self.get_object()

        if alert.resolved_at:
            return Response(
                {"detail": "Alert is already resolved"},
                status=status.HTTP_400_BAD_REQUEST,
            )

        alert.resolved_at = timezone.now()
        alert.resolved_by = request.user
        alert.save()

        serializer = self.get_serializer(alert)
        return Response(serializer.data)
