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

from apps.banking.models import ChequeLeaf
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.cheque_books.service import ChequeBookService
from apps.treasury.cheques.models import ChequeCancellation, ChequeClearingEvent


class ChequeLeafService:
    @staticmethod
    @transaction.atomic
    def reserve_leaf(*, leaf: ChequeLeaf, user, reason: str = "") -> ChequeLeaf:
        leaf = ChequeLeaf.objects.select_for_update().get(pk=leaf.pk)
        if leaf.direction != ChequeLeaf.Direction.ISSUED:
            raise ValidationError("Only issued cheque book leaves can be reserved.")
        if leaf.status != ChequeLeaf.Status.AVAILABLE:
            raise ValidationError(f"Cheque leaf {leaf.cheque_number} is {leaf.status} and cannot be reserved.")
        leaf.status = ChequeLeaf.Status.RESERVED
        leaf.purpose = reason or leaf.purpose
        leaf.save(update_fields=["status", "purpose", "updated_at"])
        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.RESERVED,
            event_date=timezone.localdate(),
            from_status=ChequeLeaf.Status.AVAILABLE,
            to_status=ChequeLeaf.Status.RESERVED,
            actor=user,
            notes=reason or "Leaf reserved before payment preparation",
        )
        ChequeBookService.sync_book_stock_status(leaf.cheque_book, actor=user)
        log_cheque_audit(
            company=leaf.company,
            action="CHEQUE_LEAF_RESERVED",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": ChequeLeaf.Status.AVAILABLE},
            new_state={"status": ChequeLeaf.Status.RESERVED},
            notes=reason,
        )
        return leaf

    @staticmethod
    @transaction.atomic
    def mark_leaf_unusable(
        *,
        leaf: ChequeLeaf,
        kind: str,
        user,
        reason: str,
    ) -> ChequeLeaf:
        """
        Mark an unused/reserved leaf as CANCELLED, SKIPPED, or LOST_DAMAGED.
        Locked permanently so it can never be reused.
        """
        if not (reason or "").strip():
            raise ValidationError("A detailed reason is required when cancelling, skipping, or retiring a leaf.")
        leaf = ChequeLeaf.objects.select_for_update().get(pk=leaf.pk)
        if leaf.status == ChequeLeaf.Status.CLEARED:
            raise ValidationError("Cleared cheques cannot be cancelled or marked damaged.")
        if leaf.status not in (
            ChequeLeaf.Status.AVAILABLE,
            ChequeLeaf.Status.RESERVED,
            ChequeLeaf.Status.PREPARED,
            ChequeLeaf.Status.APPROVED,
        ):
            raise ValidationError(
                f"Leaf {leaf.cheque_number} is {leaf.status}; use the post-issue cancellation/stop-payment workflow."
            )

        status_map = {
            "CANCELLED": (ChequeLeaf.Status.CANCELLED, ChequeCancellation.CancellationKind.UNUSED_CANCEL),
            "SKIPPED": (ChequeLeaf.Status.SKIPPED, ChequeCancellation.CancellationKind.SKIPPED),
            "LOST_DAMAGED": (ChequeLeaf.Status.LOST_DAMAGED, ChequeCancellation.CancellationKind.DAMAGED),
            "DAMAGED": (ChequeLeaf.Status.LOST_DAMAGED, ChequeCancellation.CancellationKind.DAMAGED),
            "LOST": (ChequeLeaf.Status.LOST_DAMAGED, ChequeCancellation.CancellationKind.LOST),
        }
        target_status, cancel_kind = status_map.get(kind.upper(), (None, None))
        if not target_status:
            raise ValidationError(f"Unsupported leaf retirement kind: {kind}")

        prev = leaf.status
        leaf.status = target_status
        leaf.bounce_reason = reason.strip()
        leaf.save(update_fields=["status", "bounce_reason", "updated_at"])

        ChequeCancellation.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            cancellation_kind=cancel_kind,
            reason=reason.strip(),
            requested_by=user,
            approved_by=user,
        )
        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.CANCELLED,
            event_date=timezone.localdate(),
            from_status=prev,
            to_status=target_status,
            actor=user,
            notes=reason.strip(),
        )
        if hasattr(leaf, "issued_profile"):
            prof = leaf.issued_profile
            prof.workflow_status = "CANCELLED"
            prof.save(update_fields=["workflow_status", "updated_at"])
        ChequeBookService.sync_book_stock_status(leaf.cheque_book, actor=user)
        log_cheque_audit(
            company=leaf.company,
            action=f"CHEQUE_LEAF_{target_status}",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev},
            new_state={"status": target_status},
            notes=reason.strip(),
        )
        return leaf

