from rest_framework import serializers
from .models import (
    StructureCityTaxSettings,
    CityTaxMonthlyRate
)

EXEMPTION_REASON_LABELS = {
    "medical": "Medical",
    "student": "Student",
    "refugee": "Refugee",
    "resident": "Resident",
    "minor": "Minor"
}


class CityTaxMonthlyRateNestedSerializer(serializers.ModelSerializer):
    class Meta:
        model = CityTaxMonthlyRate
        fields = ["year", "month", "rate"]

    def validate_month(self, value):
        if not 1 <= value <= 12:
            raise serializers.ValidationError("Month must be between 1 and 12")
        return value
    
class StructureCityTaxSettingsSerializer(serializers.ModelSerializer):
    city_taxes = CityTaxMonthlyRateNestedSerializer(
        many=True,
        required=False
    )

    class Meta:
        model = StructureCityTaxSettings
        fields = [
            "default_rate",
            "max_taxable_nights",
            "minor_age_limit",
            "exemption_reasons",
            "platform_exemptions",
            "city_taxes",
            "is_active",
        ]

    def validate_exemption_reasons(self, value):
        if value in (None, serializers.empty):
            return []

        normalized = []
        for reason in value:
            reason_key = str(reason).strip().lower()
            if reason_key not in EXEMPTION_REASON_LABELS:
                raise serializers.ValidationError(
                    "Exemption reasons must be one of: Medical, Student, Refugee, Resident."
                )
            normalized.append(EXEMPTION_REASON_LABELS[reason_key])

        return list(dict.fromkeys(normalized))

    def validate_platform_exemptions(self, value):
        if value in (None, serializers.empty):
            return []

        normalized = [str(item).strip().lower() for item in value if str(item).strip()]
        return list(dict.fromkeys(normalized))

    def create(self, validated_data):
        city_taxes = validated_data.pop("city_taxes", [])
        structure = self.context["structure"]

        settings = StructureCityTaxSettings.objects.create(
            structure=structure,
            **validated_data
        )

        self._save_city_taxes(settings, structure, city_taxes)
        return settings

    def update(self, instance, validated_data):
        city_taxes = validated_data.pop("city_taxes", None)

        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        instance.save()

        if city_taxes is not None:
            # Replace all monthly rates safely
            CityTaxMonthlyRate.objects.filter(
                structure=instance.structure
            ).delete()

            self._save_city_taxes(instance, instance.structure, city_taxes)

        return instance

    def _save_city_taxes(self, settings, structure, city_taxes):
        for tax in city_taxes:
            CityTaxMonthlyRate.objects.create(
                structure=structure,
                settings=settings,
                year=tax["year"],
                month=tax["month"],
                rate=tax["rate"],
            )
