"""
Milestone serializers for timeline events.
"""

from rest_framework import serializers

from apps.core.models import Milestone


class MilestoneSerializer(serializers.ModelSerializer):
    """Serializer for Milestone model matching frontend milestoneValidationSchema."""

    class Meta:
        model = Milestone
        fields = [
            "id",
            "title",
            "description",
            "event_type",
            "event_date",
            "event_date_precision",
            "entity_type",
            "entity_id",
            "is_public",
            "display_order",
            "from_value",
            "to_value",
            "from_entity_id",
            "to_entity_id",
            "from_location_id",
            "to_location_id",
            "created_at",
            "updated_at",
        ]
        read_only_fields = ["id", "created_at", "updated_at"]


class MilestoneCreateSerializer(serializers.ModelSerializer):
    """Serializer for creating milestones."""

    class Meta:
        model = Milestone
        fields = [
            "title",
            "description",
            "event_type",
            "event_date",
            "event_date_precision",
            "entity_type",
            "entity_id",
            "is_public",
            "display_order",
            "from_value",
            "to_value",
            "from_entity_id",
            "to_entity_id",
            "from_location_id",
            "to_location_id",
        ]

    def validate(self, attrs):
        """Validate change events have from/to values."""
        change_events = ["name_change", "operator_change", "owner_change", "location_change", "status_change"]
        if attrs.get("event_type") in change_events:
            has_change_data = (
                attrs.get("from_value")
                or attrs.get("to_value")
                or attrs.get("from_entity_id")
                or attrs.get("to_entity_id")
                or attrs.get("from_location_id")
                or attrs.get("to_location_id")
            )
            if not has_change_data:
                raise serializers.ValidationError(
                    "Change events must specify what changed (from/to values or entity IDs)"
                )
        return attrs


class MilestoneListSerializer(serializers.ModelSerializer):
    """Lightweight serializer for listing milestones."""

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