from decimal import Decimal

from django.core.exceptions import ValidationError
from django.db.models import Sum


def account_balance(account):
    totals = account.transactions.values("transaction_type").annotate(total=Sum("converted_amount"))
    mapped = {row["transaction_type"]: Decimal(row["total"] or 0) for row in totals}
    return Decimal(account.opening_balance or 0) + mapped.get("credit", Decimal("0")) - mapped.get("debit", Decimal("0"))


def ensure_debit_allowed(account, amount, *, label="payment"):
    amount = Decimal(amount or 0)
    current = account_balance(account)
    projected = current - amount
    if projected < 0 and not account.allow_overdraft:
        raise ValidationError({
            "financial_account": (
                f"{label.title()} would make {account.name} negative. Current balance: "
                f"{current} {account.currency.title}; required deduction: {amount}. "
                "Use another account or explicitly enable overdraft on this account."
            )
        })
    return current, projected
