from datetime import date
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils import timezone

from apps.accounting.models import Voucher
from apps.accounting.services import PostingService
from apps.banking.models import ChequeLeaf
from apps.party_hub.services.sync import OpenItemSyncService
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.cheque_leaves.service import ChequeLeafService
from apps.treasury.cheques.issued_cheques.service import IssuedChequeService
from apps.treasury.cheques.models import (
    ChequeCancellation,
    ChequeClearingEvent,
    IssuedCheque,
    ReceivedCheque,
)


class ChequeCancellationService:
    @staticmethod
    @transaction.atomic
    def cancel_cheque(
        *,
        leaf: ChequeLeaf,
        user,
        reason: str,
        kind: str = "CANCELLED",
        cancel_date: date | None = None,
        bank_stop_ref: str = "",
    ) -> ChequeLeaf:
        if not (reason or "").strip():
            raise ValidationError("Cancellation reason is mandatory.")
        leaf = ChequeLeaf.objects.select_for_update().get(pk=leaf.pk)
        if leaf.status == ChequeLeaf.Status.CLEARED:
            raise ValidationError("Cleared cheques cannot be cancelled.")

        if leaf.status in (
            ChequeLeaf.Status.AVAILABLE,
            ChequeLeaf.Status.RESERVED,
            ChequeLeaf.Status.PREPARED,
            ChequeLeaf.Status.APPROVED,
        ):
            return ChequeLeafService.mark_leaf_unusable(leaf=leaf, kind=kind, user=user, reason=reason)

        if kind.upper() == "STOP_PAYMENT":
            return IssuedChequeService.stop_payment(
                leaf=leaf,
                user=user,
                reason=reason,
                stop_date=cancel_date,
                bank_stop_ref=bank_stop_ref,
            )

        d = cancel_date or timezone.localdate()
        prev = leaf.status
        rev_v = None
        if leaf.voucher and leaf.voucher.status == Voucher.Status.POSTED and not leaf.reversal_voucher_id:
            OpenItemSyncService.release_allocations_for_reversal(
                voucher=leaf.voucher,
                reason=f"Cancelled cheque #{leaf.cheque_number}: {reason}",
            )
            rev_v = PostingService.reverse_voucher(
                voucher=leaf.voucher,
                user=user,
                reversal_date=d,
                reason=f"Cancel cheque #{leaf.cheque_number}: {reason}",
            )
            leaf.reversal_voucher = rev_v

        leaf.status = ChequeLeaf.Status.CANCELLED
        leaf.bounce_reason = reason.strip()
        leaf.save(update_fields=["status", "reversal_voucher", "bounce_reason", "updated_at"])

        if hasattr(leaf, "issued_profile"):
            prof = leaf.issued_profile
            prof.workflow_status = IssuedCheque.WorkflowStatus.CANCELLED
            prof.save(update_fields=["workflow_status", "updated_at"])
        if hasattr(leaf, "received_profile"):
            prof = leaf.received_profile
            prof.workflow_status = ReceivedCheque.WorkflowStatus.CANCELLED
            prof.save(update_fields=["workflow_status", "updated_at"])

        ChequeCancellation.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            cancellation_kind=(
                ChequeCancellation.CancellationKind.ISSUED_CANCEL
                if leaf.direction == ChequeLeaf.Direction.ISSUED
                else ChequeCancellation.CancellationKind.UNUSED_CANCEL
            ),
            reason=reason.strip(),
            bank_stop_ref=bank_stop_ref,
            requested_by=user,
            approved_by=user,
            reversal_voucher=rev_v,
        )
        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.CANCELLED,
            event_date=d,
            from_status=prev,
            to_status=ChequeLeaf.Status.CANCELLED,
            voucher=rev_v,
            actor=user,
            notes=reason.strip(),
        )
        log_cheque_audit(
            company=leaf.company,
            action="CHEQUE_CANCELLED",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev},
            new_state={"status": ChequeLeaf.Status.CANCELLED, "reason": reason.strip()},
        )
        return leaf

