from rest_framework import serializers

from .models import FarmAlertNotification


class IncomingAlertSerializer(serializers.Serializer):
    alert_id = serializers.CharField(required=False, allow_blank=True, help_text="شناسه هشدار")
    level = serializers.CharField(required=False, allow_blank=True, help_text="سطح هشدار")
    title = serializers.CharField(required=False, allow_blank=True, help_text="عنوان هشدار")
    message = serializers.CharField(required=False, allow_blank=True, help_text="متن هشدار")
    suggested_action = serializers.CharField(required=False, allow_blank=True, help_text="اقدام پیشنهادی")
    source_metric_type = serializers.CharField(required=False, allow_blank=True, help_text="نوع شاخص")
    timestamp = serializers.DateTimeField(required=False, allow_null=True, help_text="زمان هشدار")
    payload = serializers.JSONField(required=False, help_text="داده تکمیلی هشدار")


class FarmAlertsRequestSerializer(serializers.Serializer):
    farm_uuid = serializers.CharField(required=False, help_text="شناسه مزرعه")
    alerts = IncomingAlertSerializer(
        many=True,
        required=False,
        help_text="لیست هشدارهای ورودی که باید در تحلیل RAG در نظر گرفته شوند",
    )

    def validate(self, attrs):
        farm_uuid = attrs.get("farm_uuid")
        if not farm_uuid:
            raise serializers.ValidationError({"farm_uuid": "farm_uuid الزامی است."})
        attrs["farm_uuid"] = farm_uuid
        attrs["alerts"] = attrs.get("alerts") or []
        return attrs


class FarmAlertNotificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = FarmAlertNotification
        fields = [
            "id",
            "farm_uuid",
            "endpoint",
            "level",
            "title",
            "message",
            "suggested_action",
            "source_alert_id",
            "source_metric_type",
            "payload",
            "created_at",
            "updated_at",
        ]
        read_only_fields = fields
