"""Financial integration boundary for the Contracts domain.

Contracts remain the source of truth for contractual terms.  Actual token
movement is delegated to the Economy domain so Contracts never mutate wallet
balances directly.
"""

from decimal import Decimal

from economy.constants import LedgerTransactionType
from economy.exceptions import (
    IdempotencyConflictError,
    InsufficientBalanceError,
    TokenBalanceOverflowError,
    WalletInactiveError,
    WalletNotFoundError,
)
from economy.services import EconomyTransferService, WalletService
from club_finance.constants import FinanceCategory
from club_finance.services import BudgetService

from .exceptions import (
    ContractFinancialError,
    ContractInsufficientFundsError,
    ContractWalletUnavailableError,
)


class ContractFinancialService:
    """Cross-domain financial operations owned by contract workflows."""

    @staticmethod
    def settle_signing_bonus(*, contract):
        """Pay a contract signing bonus exactly once.

        The caller is expected to execute this inside the same outer database
        transaction that creates/accepts the contract.  EconomyTransferService
        supplies wallet locking, balance conservation, immutable ledger
        history and idempotency.

        A zero signing bonus intentionally creates no wallet and no ledger
        entry because there is no financial movement to record.
        """

        amount = contract.signing_bonus

        if amount == Decimal("0"):
            return None

        try:
            budget_check = BudgetService.check_spend(
                club=contract.club,
                category=FinanceCategory.SIGNING_BONUS,
                amount=amount,
            )
            if not budget_check["allowed"]:
                raise ContractFinancialError(
                    "Signing bonus exceeds the club hard budget limit."
                )
            club_wallet = WalletService.get_or_create_club_wallet(
                club=contract.club,
            )
            player_wallet = WalletService.get_or_create_player_wallet(
                player=contract.player,
            )

            return EconomyTransferService.transfer(
                source_wallet=club_wallet,
                destination_wallet=player_wallet,
                amount=amount,
                transaction_type=LedgerTransactionType.CONTRACT_SIGNING_BONUS,
                reference_type="contract",
                reference_id=str(contract.pk),
                # Source offer is stable for the logical acceptance operation,
                # while a contract UUID could be regenerated after a rollback.
                idempotency_key=(
                    f"contract-signing-bonus:{contract.source_offer_id}"
                ),
                description="Contract signing bonus",
            )

        except InsufficientBalanceError as exc:
            raise ContractInsufficientFundsError(
                "Club wallet does not have enough available balance for the "
                "contract signing bonus."
            ) from exc
        except (WalletInactiveError, WalletNotFoundError) as exc:
            raise ContractWalletUnavailableError(
                "Contract signing bonus requires active club and player "
                "wallets."
            ) from exc
        except (IdempotencyConflictError, TokenBalanceOverflowError) as exc:
            raise ContractFinancialError(
                "Contract signing bonus could not be settled safely."
            ) from exc
