"""
Serializers for Incident management API endpoints.
"""

from rest_framework import serializers

from apps.core.models import Incident, IncidentAlert


class IncidentAlertSerializer(serializers.ModelSerializer):
    """Serializer for linked alerts within an incident."""

    class Meta:
        model = IncidentAlert
        fields = [
            "id",
            "alert_source",
            "alert_id",
            "created_at",
        ]
        read_only_fields = ["id", "created_at"]


class IncidentSerializer(serializers.ModelSerializer):
    """Serializer for Incident model."""

    acknowledged_by_username = serializers.CharField(
        source="acknowledged_by.username", read_only=True, allow_null=True
    )
    resolved_by_username = serializers.CharField(
        source="resolved_by.username", read_only=True, allow_null=True
    )
    status_display = serializers.CharField(source="get_status_display", read_only=True)
    severity_display = serializers.CharField(source="get_severity_display", read_only=True)
    linked_alerts = IncidentAlertSerializer(many=True, read_only=True)

    class Meta:
        model = Incident
        fields = [
            "id",
            "incident_number",
            "title",
            "description",
            "severity",
            "severity_display",
            "status",
            "status_display",
            "detected_at",
            "acknowledged_at",
            "acknowledged_by",
            "acknowledged_by_username",
            "resolved_at",
            "resolved_by",
            "resolved_by_username",
            "resolution_notes",
            "alert_count",
            "linked_alerts",
            "created_at",
            "updated_at",
        ]
        read_only_fields = [
            "id",
            "incident_number",
            "detected_at",
            "acknowledged_at",
            "acknowledged_by",
            "resolved_at",
            "resolved_by",
            "alert_count",
            "created_at",
            "updated_at",
        ]


class IncidentCreateSerializer(serializers.ModelSerializer):
    """Serializer for creating incidents with linked alerts."""

    alert_ids = serializers.ListField(
        child=serializers.UUIDField(),
        write_only=True,
        required=False,
        help_text="List of alert IDs to link to this incident",
    )
    alert_sources = serializers.ListField(
        child=serializers.ChoiceField(choices=["system", "rate_limit"]),
        write_only=True,
        required=False,
        help_text="Source types for each alert (must match alert_ids length)",
    )

    class Meta:
        model = Incident
        fields = [
            "title",
            "description",
            "severity",
            "alert_ids",
            "alert_sources",
        ]

    def validate(self, data):
        alert_ids = data.get("alert_ids", [])
        alert_sources = data.get("alert_sources", [])

        if alert_ids and len(alert_ids) != len(alert_sources):
            raise serializers.ValidationError(
                {"alert_sources": "Must provide one source per alert_id"}
            )

        return data

    def create(self, validated_data):
        alert_ids = validated_data.pop("alert_ids", [])
        alert_sources = validated_data.pop("alert_sources", [])

        incident = Incident.objects.create(**validated_data)

        # Create linked alerts
        for alert_id, source in zip(alert_ids, alert_sources):
            IncidentAlert.objects.create(
                incident=incident,
                alert_id=alert_id,
                alert_source=source,
            )

        return incident


class IncidentAcknowledgeSerializer(serializers.Serializer):
    """Serializer for acknowledging an incident."""

    pass  # No additional data needed


class IncidentResolveSerializer(serializers.Serializer):
    """Serializer for resolving an incident."""

    resolution_notes = serializers.CharField(required=False, allow_blank=True)
    resolve_alerts = serializers.BooleanField(
        default=True,
        help_text="Whether to also resolve all linked alerts",
    )


class LinkAlertsSerializer(serializers.Serializer):
    """Serializer for linking alerts to an incident."""

    alert_ids = serializers.ListField(
        child=serializers.UUIDField(),
        help_text="List of alert IDs to link",
    )
    alert_sources = serializers.ListField(
        child=serializers.ChoiceField(choices=["system", "rate_limit"]),
        help_text="Source types for each alert",
    )

    def validate(self, data):
        if len(data["alert_ids"]) != len(data["alert_sources"]):
            raise serializers.ValidationError(
                {"alert_sources": "Must provide one source per alert_id"}
            )
        return data
