from apps.treasury.cheques.models import ChequeAuditLog
from apps.treasury.models import record_treasury_audit


def log_cheque_audit(
    *,
    company,
    action: str,
    actor=None,
    cheque_leaf=None,
    cheque_book=None,
    previous_state: dict | None = None,
    new_state: dict | None = None,
    notes: str = "",
):
    ChequeAuditLog.objects.create(
        company=company,
        cheque_leaf=cheque_leaf,
        cheque_book=cheque_book,
        action=action,
        actor=actor,
        previous_state=previous_state,
        new_state=new_state,
        notes=(notes or "")[:255],
    )
    record_treasury_audit(
        company=company,
        module="CHEQUES",
        action=action,
        entity_type="ChequeLeaf" if cheque_leaf else "ChequeBook",
        entity_id=str(cheque_leaf.id if cheque_leaf else (cheque_book.id if cheque_book else company.id)),
        actor=actor,
        previous_state=previous_state,
        new_state=new_state,
        notes=notes,
    )

