"""Audit-trail writer. Called from routers after a state change."""
from typing import Any

from sqlalchemy.orm import Session

from app.core.time import utcnow
from app.models.audit import AuditLog


def record(
    db: Session,
    *,
    user_id: int | None,
    action: str,
    entity_type: str,
    entity_id: int | None = None,
    payload: dict[str, Any] | None = None,
    ip_address: str | None = None,
    commit: bool = False,
) -> AuditLog:
    """Append an audit row. The caller owns the transaction unless commit=True."""
    entry = AuditLog(
        user_id=user_id,
        action=action,
        entity_type=entity_type,
        entity_id=entity_id,
        payload=payload,
        ip_address=ip_address,
        created_at=utcnow(),
    )
    db.add(entry)
    if commit:
        db.commit()
    else:
        db.flush()
    return entry
