from rest_framework import serializers

from shop_management.models.data.accounting import LedgerAccount
from shop_management.serializers.data.base import DataRootSerializer


class LedgerAccountSerializer(DataRootSerializer):
    shop_name = serializers.ReadOnlyField(source="shop.name")
    parent_code = serializers.ReadOnlyField(source="parent.code")
    parent_name = serializers.ReadOnlyField(source="parent.name")
    child_count = serializers.IntegerField(read_only=True)

    class Meta:
        model = LedgerAccount
        fields = "__all__"
        read_only_fields = ("created_by", "is_system")

    def validate(self, attrs):
        shop = attrs.get("shop") or getattr(self.instance, "shop", None)
        parent = attrs.get("parent") if "parent" in attrs else getattr(self.instance, "parent", None)
        account_type = attrs.get("account_type") or getattr(self.instance, "account_type", None)
        if parent and parent.shop_id != shop.id:
            raise serializers.ValidationError({"parent": "Parent account must belong to the same branch."})
        if parent and parent.account_type != account_type:
            raise serializers.ValidationError({"account_type": "Account type must match its parent."})
        return attrs
