"""审计写入门面。

每个 admin 写操作调一次 write_audit,把"谁(admin)在哪个 IP 对什么(target)做了什么
(action)+ 前后值(detail)"落进 admin_audit_log。

⚠️ 涉钱/涉状态的写操作:传 commit=False,和业务写操作放同一事务一起 commit,
保证"改了就有痕、有痕就改了"原子(见 plan 风险点 1)。轻量操作可 commit=True。
"""
from __future__ import annotations

from sqlalchemy.orm import Session

from app.admin.repositories import audit_log as audit_repo
from app.models.admin import AdminUser


def write_audit(
    db: Session,
    admin: AdminUser,
    *,
    action: str,
    target_type: str,
    target_id: str | int | None = None,
    detail: dict | None = None,
    ip: str | None = None,
    commit: bool = True,
) -> None:
    audit_repo.add_audit_log(
        db,
        admin_id=admin.id,
        admin_username=admin.username,
        action=action,
        target_type=target_type,
        target_id=str(target_id) if target_id is not None else None,
        detail=detail,
        ip=ip,
        commit=commit,
    )
