"""Centralized audit logging for admin and destructive actions."""
from uuid import UUID
from typing import Optional
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.audit_log import AuditLog


async def log_audit(
    db: AsyncSession,
    user_id: UUID,
    action: str,
    resource_type: str,
    resource_id: Optional[UUID] = None,
    details: Optional[dict] = None,
    account_id: Optional[UUID] = None,
) -> None:
    """Record an audit log entry. Does not commit — piggybacks on the caller's commit."""
    if account_id is None:
        # Derive from the acting user's account as a fallback (one extra query).
        from sqlalchemy import select
        from app.models.user import User
        result = await db.execute(select(User.account_id).where(User.id == user_id))
        account_id = result.scalar_one()

    entry = AuditLog(
        user_id=user_id,
        account_id=account_id,
        action=action,
        resource_type=resource_type,
        resource_id=resource_id,
        details=details,
    )
    db.add(entry)
