from rest_framework import serializers
from django.db import IntegrityError
from shop_management.models.data.customer import Customer
from shop_management.serializers.data.base import DataRootSerializer
from shop_management.models.data.utils import Unit, Currency, ExchangeRate

class UnitSerializer(DataRootSerializer):
    
    class Meta:
        model = Unit
        fields = '__all__'


class CurrencySerializer(DataRootSerializer):
    shop_name = serializers.ReadOnlyField(source="shop.name")
    
    class Meta:
        model = Currency
        fields = '__all__'

    def validate(self, attrs):
        attrs = super().validate(attrs)
        title = str(attrs.get("title") or getattr(self.instance, "title", "")).strip()
        shop = attrs.get("shop") or getattr(self.instance, "shop", None)
        if not title:
            raise serializers.ValidationError({"title": "Currency name is required."})
        duplicate = Currency.objects.filter(shop=shop, title__iexact=title)
        if self.instance:
            duplicate = duplicate.exclude(pk=self.instance.pk)
        if duplicate.exists():
            raise serializers.ValidationError(
                {"title": "This currency already exists for the selected branch."}
            )
        attrs["title"] = title
        return attrs


class ExchangeRateSerializer(DataRootSerializer):
    from_currency_title = serializers.ReadOnlyField(source="from_currency.title")
    to_currency_title = serializers.ReadOnlyField(source="to_currency.title")
    shop_name = serializers.ReadOnlyField(source="shop.name")

    class Meta:
        model = ExchangeRate
        fields = [
            "id",
            "from_currency",
            "to_currency",
            "from_currency_title",
            "to_currency_title",
            "rate",
            "rate_date",
            "shop",
            "shop_name",
        ]

    def validate(self, attrs):
        from_currency = attrs.get("from_currency") or getattr(self.instance, "from_currency", None)
        to_currency = attrs.get("to_currency") or getattr(self.instance, "to_currency", None)
        shop = attrs.get("shop") or getattr(self.instance, "shop", None)

        if from_currency and to_currency and from_currency.id == to_currency.id:
            raise serializers.ValidationError(
                {"to_currency": "From currency and To currency cannot be the same."}
            )

        if shop and from_currency and from_currency.shop_id != shop.id:
            raise serializers.ValidationError(
                {"from_currency": "From currency does not belong to the selected shop."}
            )

        if shop and to_currency and to_currency.shop_id != shop.id:
            raise serializers.ValidationError(
                {"to_currency": "To currency does not belong to the selected shop."}
            )

        return attrs

    def create(self, validated_data):
        try:
            return super().create(validated_data)
        except IntegrityError:
            raise serializers.ValidationError(
                {"non_field_errors": ["An exchange rate for this shop/currency pair/date already exists."]}
            )

    def update(self, instance, validated_data):
        try:
            return super().update(instance, validated_data)
        except IntegrityError:
            raise serializers.ValidationError(
                {"non_field_errors": ["An exchange rate for this shop/currency pair/date already exists."]}
            )
