from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Dict, Optional

from . import db as _app_db


@dataclass
class AuditEvent:
    event: str
    operator_id: str
    operator_id_missing: bool = False
    ip: Optional[str] = None
    chat_id: Optional[str] = None
    node_id: Optional[str] = None
    agent_id: Optional[str] = None
    status: str = "ok"
    error_code: Optional[str] = None
    duration_ms: Optional[int] = None
    data: Dict[str, Any] = field(default_factory=dict)


async def audit_log(audit_event: AuditEvent) -> Dict[str, Any]:
    return await _app_db.append_audit_event(
        audit_event.event,
        audit_event.operator_id,
        operator_id_missing=bool(audit_event.operator_id_missing),
        ip=audit_event.ip,
        chat_id=audit_event.chat_id,
        node_id=audit_event.node_id,
        agent_id=audit_event.agent_id,
        status=audit_event.status,
        error_code=audit_event.error_code,
        duration_ms=audit_event.duration_ms,
        data=audit_event.data,
    )
