"""Player-funded release; the employment exit and ledger payment are atomic."""

from django.db import transaction
from django.utils import timezone

from economy.constants import LedgerTransactionType
from economy.exceptions import EconomyError
from economy.services import EconomyTransferService, WalletService

from .constants import ContractStatus, ContractTerminationReason
from .exceptions import ContractTermsError
from .services import ContractLifecycleService, _lock_contract_with_participants
from .validators import validate_money


@transaction.atomic
def exercise_release(*, contract_id, actor, maximum_payment, wallet_type="PLAYER"):
    contract = _lock_contract_with_participants(contract_id)
    if contract.player.career.user_id != actor.pk:
        raise ContractTermsError("Only the player may exercise a release clause.")
    if (
        contract.status != ContractStatus.ACTIVE
        or not contract.start_date <= timezone.localdate() < contract.end_date
    ):
        raise ContractTermsError(
            "Release requires a currently effective active contract."
        )
    amount = contract.release_clause
    if amount is None or amount <= 0:
        raise ContractTermsError("An agreed positive release clause is required.")
    if amount > validate_money(maximum_payment, "maximum_payment"):
        raise ContractTermsError("Release amount exceeds the approved payment limit.")
    if wallet_type not in ("PLAYER", "ACCOUNT"):
        raise ContractTermsError("Release must be funded by the player's own wallet.")
    from marketplace.services import MarketWallets

    try:
        payer = (
            WalletService.get_or_create_player_wallet(player=contract.player)
            if wallet_type == "PLAYER"
            else MarketWallets.account(actor)
        )
        recipient = WalletService.get_or_create_club_wallet(club=contract.club)
        EconomyTransferService.transfer(
            source_wallet=payer,
            destination_wallet=recipient,
            amount=amount,
            transaction_type=LedgerTransactionType.CONTRACT_RELEASE_PAYMENT,
            reference_type="contract",
            reference_id=str(contract.pk),
            idempotency_key=f"contract-release:{contract.pk}",
            description="Agreed player release clause",
        )
    except EconomyError as exc:
        raise ContractTermsError(f"Release payment failed: {exc}") from exc
    return ContractLifecycleService.terminate_contract(
        contract_id=contract.pk,
        reason=ContractTerminationReason.RELEASE_CLAUSE,
    )
