from rest_framework import serializers
from decimal import Decimal

from shop_management.models.data.shop_account import Account
from shop_management.serializers.data.base import DataRootSerializer


class AccountSerializer(DataRootSerializer):
    shop_name = serializers.ReadOnlyField(source="shop.name")
    currency_title = serializers.ReadOnlyField(source="currency.title")
    balance = serializers.SerializerMethodField()

    class Meta:
        model = Account
        fields = [
            "id",
            "shop",
            "shop_name",
            "name",
            "account_type",
            "bank_name",
            "account_number",
            "sarafi_name",
            "is_active",
            "is_system_account",
            "allow_overdraft",
            "currency",
            "currency_title",
            "opening_balance",
            "balance",
            "note",
        ]
        read_only_fields = ["is_system_account"]

    def get_balance(self, obj):
        credit_total = (
            obj.transactions.filter(transaction_type="credit")
            .values_list("converted_amount", flat=True)
        )
        debit_total = (
            obj.transactions.filter(transaction_type="debit")
            .values_list("converted_amount", flat=True)
        )
        return obj.opening_balance + sum(credit_total, Decimal("0")) - sum(
            debit_total, Decimal("0")
        )

    def validate(self, attrs):
        shop = attrs.get("shop")
        currency = attrs.get("currency")
        if self.instance:
            if shop is None:
                shop = self.instance.shop
            if currency is None:
                currency = self.instance.currency
        if shop and currency and currency.shop_id != shop.pk:
            raise serializers.ValidationError(
                {"currency": "Currency must belong to the selected shop."}
            )
        return attrs
