import uuid

from sqlalchemy.ext.asyncio import AsyncSession

from app.models.audit import AuditLogEntry


async def write_audit_log(
    db: AsyncSession,
    tenant_id: uuid.UUID,
    actor_id: uuid.UUID | None,
    action: str,
    entity_type: str | None = None,
    entity_id: uuid.UUID | None = None,
    details: dict | None = None,
) -> None:
    """
    Append-only audit trail entry (NFR-SEC-004: logins, permission changes,
    data exports, record deletions; NFR-AUD-001). Called from inside the
    same request transaction as the action it records, so it rolls back
    together with a failed action rather than ever recording one that didn't
    actually happen.
    """
    db.add(
        AuditLogEntry(
            tenant_id=tenant_id,
            actor_id=actor_id,
            action=action,
            entity_type=entity_type,
            entity_id=entity_id,
            details=details,
        )
    )
    await db.flush()
