import uuid
from decimal import Decimal
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models


class IssuedCheque(models.Model):
    class PayeeType(models.TextChoices):
        SUPPLIER = "SUPPLIER", "Supplier"
        CONTRACTOR = "CONTRACTOR", "Subcontractor / Contractor"
        EMPLOYEE = "EMPLOYEE", "Employee Salary / Expense"
        CUSTOMER = "CUSTOMER", "Customer Refund"
        OTHER = "OTHER", "Other Payee"

    class WorkflowStatus(models.TextChoices):
        RESERVED = "RESERVED", "Leaf Reserved"
        PREPARED = "PREPARED", "Payment Voucher Prepared"
        PENDING_APPROVAL = "PENDING_APPROVAL", "Pending Signatory Authorization"
        APPROVED = "APPROVED", "Authorized for Issuance"
        ISSUED = "ISSUED", "Issued / Handed Over"
        PRESENTED = "PRESENTED", "Presented at Bank"
        CLEARED = "CLEARED", "Cleared & Reconciled"
        BOUNCED = "BOUNCED", "Returned / Bounced"
        STOP_PAYMENT = "STOP_PAYMENT", "Stop Payment Requested"
        CANCELLED = "CANCELLED", "Cancelled"
        STALE = "STALE", "Stale-Dated"
        REPLACED = "REPLACED", "Replaced"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="issued_cheques")
    leaf = models.OneToOneField("banking.ChequeLeaf", on_delete=models.CASCADE, related_name="issued_profile")
    cheque_book = models.ForeignKey("banking.ChequeBook", on_delete=models.SET_NULL, null=True, blank=True)
    bank_account = models.ForeignKey("banking.BankAccount", on_delete=models.PROTECT)
    payee_type = models.CharField(max_length=16, choices=PayeeType.choices, default=PayeeType.SUPPLIER)
    party = models.ForeignKey("accounting.Party", on_delete=models.SET_NULL, null=True, blank=True)
    employee = models.ForeignKey("hr.EmployeeDetail", on_delete=models.SET_NULL, null=True, blank=True)
    payee_name = models.CharField(max_length=200)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    currency = models.CharField(max_length=3, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))
    cheque_date = models.DateField(db_index=True)
    issue_date = models.DateField(null=True, blank=True)
    expected_presentation_date = models.DateField(null=True, blank=True)
    payment_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="issued_cheque_profiles"
    )
    invoice_reference = models.CharField(max_length=160, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    purpose = models.CharField(max_length=255, blank=True)
    prepared_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="prepared_issued_cheques"
    )
    authorized_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="authorized_issued_cheques"
    )
    secondary_authorized_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="countersigned_cheques"
    )
    workflow_status = models.CharField(
        max_length=24, choices=WorkflowStatus.choices, default=WorkflowStatus.RESERVED, db_index=True
    )
    stop_payment_ref = models.CharField(max_length=80, blank=True)
    stop_payment_date = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "issued_cheques"
        ordering = ["-cheque_date", "-created_at"]


class ReceivedCheque(models.Model):
    class WorkflowStatus(models.TextChoices):
        RECEIVED = "RECEIVED", "Received"
        VERIFIED = "VERIFIED", "Verified (Cheques-in-Hand)"
        IN_HAND = "IN_HAND", "Cheques-in-Hand"
        DEPOSITED = "DEPOSITED", "Deposited at Bank"
        UNDER_CLEARING = "UNDER_CLEARING", "Cheques-in-Clearing"
        CLEARED = "CLEARED", "Cleared to Bank Account"
        BOUNCED = "BOUNCED", "Bounced / Returned"
        CANCELLED = "CANCELLED", "Cancelled"
        STALE = "STALE", "Stale-Dated"
        REPLACED = "REPLACED", "Replaced"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="received_cheques")
    leaf = models.OneToOneField("banking.ChequeLeaf", on_delete=models.CASCADE, related_name="received_profile")
    deposit_bank_account = models.ForeignKey("banking.BankAccount", on_delete=models.PROTECT)
    drawer_name = models.CharField(max_length=200)
    drawer_bank = models.CharField(max_length=150)
    drawer_branch = models.CharField(max_length=120, blank=True)
    drawer_account_encrypted = models.TextField(blank=True)
    drawer_account_masked = models.CharField(max_length=40, blank=True)
    drawer_account_fingerprint = models.CharField(max_length=64, blank=True, db_index=True)
    customer = models.ForeignKey("accounting.Party", on_delete=models.SET_NULL, null=True, blank=True)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    currency = models.CharField(max_length=3, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))
    cheque_date = models.DateField(db_index=True)
    received_date = models.DateField(db_index=True)
    receipt_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="received_cheque_profiles"
    )
    invoice_references = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    deposit_slip_no = models.CharField(max_length=80, blank=True)
    workflow_status = models.CharField(
        max_length=24, choices=WorkflowStatus.choices, default=WorkflowStatus.IN_HAND, db_index=True
    )
    duplicate_warning = models.BooleanField(default=False)
    duplicate_warning_reason = models.CharField(max_length=255, blank=True)
    verified_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="verified_received_cheques"
    )
    verified_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "received_cheques"
        ordering = ["-received_date", "-created_at"]


class ChequeDepositBatch(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft Batch"
        VERIFIED = "VERIFIED", "Verified"
        DEPOSITED = "DEPOSITED", "Deposited / Under Clearing"
        PARTIAL_CLEARED = "PARTIAL_CLEARED", "Partially Cleared"
        CLEARED = "CLEARED", "Fully Cleared"
        PARTIAL_BOUNCED = "PARTIAL_BOUNCED", "Contains Bounced Items"
        CLOSED = "CLOSED", "Closed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_deposit_batches")
    batch_no = models.CharField(max_length=40, db_index=True)
    deposit_bank_account = models.ForeignKey("banking.BankAccount", on_delete=models.PROTECT)
    bank_branch_name = models.CharField(max_length=120, blank=True)
    deposit_slip_no = models.CharField(max_length=80)
    deposit_date = models.DateField(db_index=True)
    total_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    cheque_count = models.PositiveIntegerField(default=0)
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.DEPOSITED, db_index=True)
    prepared_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="prepared_deposit_batches")
    verified_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="verified_deposit_batches"
    )
    verified_at = models.DateTimeField(null=True, blank=True)
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "cheque_deposit_batches"
        unique_together = [("company", "batch_no")]
        ordering = ["-deposit_date", "-created_at"]


class ChequeDepositLine(models.Model):
    class LineStatus(models.TextChoices):
        QUEUED = "QUEUED", "Queued"
        DEPOSITED = "DEPOSITED", "Deposited"
        UNDER_CLEARING = "UNDER_CLEARING", "Under Clearing"
        CLEARED = "CLEARED", "Cleared"
        BOUNCED = "BOUNCED", "Bounced / Returned"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    batch = models.ForeignKey(ChequeDepositBatch, on_delete=models.CASCADE, related_name="lines")
    cheque_leaf = models.ForeignKey("banking.ChequeLeaf", on_delete=models.CASCADE, related_name="deposit_lines")
    received_cheque = models.ForeignKey(
        ReceivedCheque, on_delete=models.SET_NULL, null=True, blank=True, related_name="deposit_lines"
    )
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    status = models.CharField(max_length=20, choices=LineStatus.choices, default=LineStatus.UNDER_CLEARING, db_index=True)
    clearing_step1_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="deposit_step1_lines"
    )
    clearing_step2_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="deposit_step2_lines"
    )
    cleared_date = models.DateField(null=True, blank=True)
    bank_reference = models.CharField(max_length=120, blank=True)
    statement_line = models.ForeignKey(
        "banking.BankStatementLine", on_delete=models.SET_NULL, null=True, blank=True, related_name="cheque_deposit_lines"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_deposit_lines"
        unique_together = [("batch", "cheque_leaf")]
        ordering = ["created_at"]


class ChequeClearingEvent(models.Model):
    class EventType(models.TextChoices):
        CREATED = "CREATED", "Registered"
        RESERVED = "RESERVED", "Leaf Reserved"
        APPROVED = "APPROVED", "Authorized"
        ISSUED = "ISSUED", "Cheque Issued"
        PRESENTED = "PRESENTED", "Presented at Bank"
        RECEIVED = "RECEIVED", "Cheque Received (Stage 0)"
        VERIFIED = "VERIFIED", "Verified"
        DEPOSITED = "DEPOSITED", "Deposited / Step 1 Clearing"
        UNDER_CLEARING = "UNDER_CLEARING", "Under Clearing"
        STATEMENT_MATCHED = "STATEMENT_MATCHED", "Statement Matched"
        CLEARED = "CLEARED", "Cleared / Step 2 Bank Credit"
        BOUNCED = "BOUNCED", "Bounced / Dishonored"
        STOP_PAYMENT = "STOP_PAYMENT", "Stop Payment"
        CANCELLED = "CANCELLED", "Cancelled"
        REPLACED = "REPLACED", "Replaced"
        REVERSED = "REVERSED", "Accounting Reversed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_clearing_events")
    cheque_leaf = models.ForeignKey("banking.ChequeLeaf", on_delete=models.CASCADE, related_name="clearing_events")
    deposit_line = models.ForeignKey(
        ChequeDepositLine, on_delete=models.SET_NULL, null=True, blank=True, related_name="events"
    )
    event_type = models.CharField(max_length=24, choices=EventType.choices, db_index=True)
    event_date = models.DateField()
    from_status = models.CharField(max_length=24, blank=True)
    to_status = models.CharField(max_length=24, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    bank_reference = models.CharField(max_length=120, blank=True)
    statement_line = models.ForeignKey("banking.BankStatementLine", on_delete=models.SET_NULL, null=True, blank=True)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_clearing_events"
        ordering = ["created_at"]


class ChequeReturn(models.Model):
    class BounceScenario(models.TextChoices):
        BEFORE_DEPOSIT = "BEFORE_DEPOSIT", "Scenario A: Bounce Before Bank Deposit"
        AFTER_DEPOSIT = "AFTER_DEPOSIT", "Scenario B: Bounce After Deposit Before Clearance"
        AFTER_CLEARANCE = "AFTER_CLEARANCE", "Scenario C: Returned / Reversed After Bank Credit"
        ISSUED_BOUNCE = "ISSUED_BOUNCE", "Issued Cheque Dishonored / Returned"

    class ApprovalStatus(models.TextChoices):
        PENDING_APPROVAL = "PENDING_APPROVAL", "Pending Bounce Reversal Approval"
        POSTED = "POSTED", "Reversal Posted"
        REJECTED = "REJECTED", "Rejected"

    class FollowUpStatus(models.TextChoices):
        OPEN = "OPEN", "Open Follow-Up"
        IN_RECOVERY = "IN_RECOVERY", "Party Notified / Recovery Active"
        REPLACED = "REPLACED", "Replaced by New Cheque"
        WRITTEN_OFF = "WRITTEN_OFF", "Written Off"
        RESOLVED = "RESOLVED", "Settled / Recovered"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_returns")
    cheque_leaf = models.ForeignKey("banking.ChequeLeaf", on_delete=models.CASCADE, related_name="bounce_records")
    deposit_line = models.ForeignKey(ChequeDepositLine, on_delete=models.SET_NULL, null=True, blank=True)
    bounce_scenario = models.CharField(max_length=24, choices=BounceScenario.choices)
    bounce_date = models.DateField(db_index=True)
    return_reason_code = models.CharField(max_length=32, default="INSUFFICIENT_FUNDS")
    return_reason = models.CharField(max_length=255)
    bank_return_reference = models.CharField(max_length=120, blank=True)
    bank_return_memo_ref = models.CharField(max_length=120, blank=True)
    bank_charge_amount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    charge_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="cheque_return_charges"
    )
    customer_notified = models.BooleanField(default=False)
    notified_at = models.DateTimeField(null=True, blank=True)
    follow_up_status = models.CharField(
        max_length=20, choices=FollowUpStatus.choices, default=FollowUpStatus.OPEN, db_index=True
    )
    follow_up_notes = models.TextField(blank=True)
    reported_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="reported_cheque_returns"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_cheque_returns"
    )
    status = models.CharField(max_length=24, choices=ApprovalStatus.choices, default=ApprovalStatus.POSTED, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_returns"
        ordering = ["-bounce_date", "-created_at"]


class ChequeReversal(models.Model):
    class StepKind(models.TextChoices):
        DEPOSIT_TRANSFER_REVERSAL = "DEPOSIT_TRANSFER_REVERSAL", "Reverse Deposit Step 1 (Dr 1035 / Cr 1036)"
        RECEIPT_REVERSAL = "RECEIPT_REVERSAL", "Reverse Original Receipt (Dr Debtors / Cr 1035)"
        BANK_CREDIT_REVERSAL = "BANK_CREDIT_REVERSAL", "Reverse Bank Credit (Dr Debtors / Cr Bank GL)"
        PAYMENT_REVERSAL = "PAYMENT_REVERSAL", "Reverse Issued Payment (Dr Bank GL / Cr Payable)"
        BANK_CHARGE = "BANK_CHARGE", "Separate Bank Return Fee (Dr Bank Charges / Cr Bank GL)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_reversals")
    cheque_leaf = models.ForeignKey("banking.ChequeLeaf", on_delete=models.CASCADE, related_name="reversals")
    cheque_return = models.ForeignKey(
        ChequeReturn, on_delete=models.SET_NULL, null=True, blank=True, related_name="reversals"
    )
    step_kind = models.CharField(max_length=32, choices=StepKind.choices)
    original_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="cheque_original_reversals"
    )
    reversal_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, related_name="cheque_reversal_entries"
    )
    reopened_allocations = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_reversals"
        ordering = ["created_at"]


class ChequeCancellation(models.Model):
    class CancellationKind(models.TextChoices):
        UNUSED_CANCEL = "UNUSED_CANCEL", "Unused Leaf Cancelled"
        ISSUED_CANCEL = "ISSUED_CANCEL", "Issued Cheque Cancelled"
        STOP_PAYMENT = "STOP_PAYMENT", "Bank Stop Payment"
        DAMAGED = "DAMAGED", "Damaged Leaf"
        LOST = "LOST", "Lost Leaf"
        SKIPPED = "SKIPPED", "Skipped Leaf"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_cancellations")
    cheque_leaf = models.ForeignKey("banking.ChequeLeaf", on_delete=models.CASCADE, related_name="cancellations")
    cancellation_kind = models.CharField(max_length=20, choices=CancellationKind.choices)
    reason = models.CharField(max_length=255)
    bank_stop_ref = models.CharField(max_length=120, blank=True)
    requested_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="requested_cheque_cancellations"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_cheque_cancellations"
    )
    reversal_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="cheque_cancellation_reversals"
    )
    cancelled_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_cancellations"
        ordering = ["-cancelled_at"]


class ChequeReplacement(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_replacements")
    original_cheque = models.ForeignKey(
        "banking.ChequeLeaf", on_delete=models.CASCADE, related_name="replaced_by_links"
    )
    replacement_cheque = models.ForeignKey(
        "banking.ChequeLeaf", on_delete=models.CASCADE, related_name="replaces_links"
    )
    reason = models.CharField(max_length=255)
    linked_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    linked_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_replacements"
        unique_together = [("original_cheque", "replacement_cheque")]
        ordering = ["-linked_at"]


class ChequeAttachment(models.Model):
    class Kind(models.TextChoices):
        CHEQUE_FRONT = "CHEQUE_FRONT", "Cheque Front Scan"
        CHEQUE_BACK = "CHEQUE_BACK", "Cheque Back / Endorsement"
        DEPOSIT_SLIP = "DEPOSIT_SLIP", "Bank Deposit Slip"
        RETURN_MEMO = "RETURN_MEMO", "Bank Return / Bounce Memo"
        STOP_LETTER = "STOP_LETTER", "Stop Payment Instruction"
        HANDOVER = "HANDOVER", "Cheque Book Handover Receipt"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_attachments")
    cheque_leaf = models.ForeignKey(
        "banking.ChequeLeaf", on_delete=models.CASCADE, null=True, blank=True, related_name="attachments"
    )
    deposit_batch = models.ForeignKey(
        ChequeDepositBatch, on_delete=models.CASCADE, null=True, blank=True, related_name="attachments"
    )
    attachment_kind = models.CharField(max_length=20, choices=Kind.choices, default=Kind.CHEQUE_FRONT)
    file_name = models.CharField(max_length=255)
    file = models.FileField(upload_to="cheque_attachments/%Y/%m/", null=True, blank=True)
    file_ref = models.CharField(max_length=255, blank=True)
    sha256_hash = models.CharField(max_length=64, blank=True)
    restricted_access = models.BooleanField(default=True)
    uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_attachments"
        ordering = ["-uploaded_at"]


class ChequeApproval(models.Model):
    class Kind(models.TextChoices):
        ISSUE_SIGN = "ISSUE_SIGN", "Cheque Issue / Signatory Authorization"
        HIGH_VALUE_DUAL_SIGN = "HIGH_VALUE_DUAL_SIGN", "Dual Signatory Authorization"
        BOUNCE_REVERSAL = "BOUNCE_REVERSAL", "Bounced Cheque Reversal Approval"
        STOP_PAYMENT = "STOP_PAYMENT", "Stop-Payment Approval"

    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending"
        APPROVED = "APPROVED", "Approved"
        REJECTED = "REJECTED", "Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_approvals")
    cheque_leaf = models.ForeignKey("banking.ChequeLeaf", on_delete=models.CASCADE, related_name="approvals")
    approval_kind = models.CharField(max_length=24, choices=Kind.choices)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING, db_index=True)
    requested_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="requested_cheque_approvals"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="decided_cheque_approvals"
    )
    payload = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    comment = models.TextField(blank=True)
    requested_at = models.DateTimeField(auto_now_add=True)
    decided_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = "cheque_approvals"
        ordering = ["-requested_at"]


class ChequeAuditLog(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_audit_logs")
    cheque_leaf = models.ForeignKey(
        "banking.ChequeLeaf", on_delete=models.SET_NULL, null=True, blank=True, related_name="audit_logs"
    )
    cheque_book = models.ForeignKey(
        "banking.ChequeBook", on_delete=models.SET_NULL, null=True, blank=True, related_name="audit_logs"
    )
    action = models.CharField(max_length=64, db_index=True)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    previous_state = models.JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)
    new_state = models.JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)
    notes = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_audit_logs"
        ordering = ["-created_at"]


class ChequeAlert(models.Model):
    class AlertType(models.TextChoices):
        LOW_BOOK_STOCK = "LOW_BOOK_STOCK", "Low Cheque Book Leaves"
        STALE_CHEQUE = "STALE_CHEQUE", "Stale-Dated Cheque"
        CLEARING_DELAYED = "CLEARING_DELAYED", "Clearing Delay Exceeded"
        BOUNCE_RECOVERY = "BOUNCE_RECOVERY", "Bounced Cheque Recovery Follow-Up"
        PENDING_APPROVAL = "PENDING_APPROVAL", "Pending Cheque Approval"

    class Severity(models.TextChoices):
        INFO = "INFO", "Info"
        WARNING = "WARNING", "Warning"
        CRITICAL = "CRITICAL", "Critical"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="cheque_alerts")
    alert_type = models.CharField(max_length=24, choices=AlertType.choices, db_index=True)
    severity = models.CharField(max_length=12, choices=Severity.choices, default=Severity.WARNING)
    cheque_leaf = models.ForeignKey("banking.ChequeLeaf", on_delete=models.CASCADE, null=True, blank=True)
    cheque_book = models.ForeignKey("banking.ChequeBook", on_delete=models.CASCADE, null=True, blank=True)
    title = models.CharField(max_length=180)
    message = models.TextField()
    is_resolved = models.BooleanField(default=False, db_index=True)
    acknowledged_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    acknowledged_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "cheque_alerts"
        ordering = ["-created_at"]
