from ..models.audit_log import AuditLog


def log_event(
    event_type: str,
    request=None,
    user_uid: str = "",
    client_id: str = "",
    metadata: dict = None,
):
    """
    Log an audit event to Firestore.

    Supported event_types:
        signin_success, signin_failure, signup_success,
        mfa_verified, mfa_failed, mfa_enrolled,
        token_issued, token_revoked, token_reuse_detected,
        session_created, session_revoked,
        device_authorized, client_registered
    """
    ip_address = ""
    user_agent = ""

    if request is not None:
        try:
            ip_address = request.environ.get('HTTP_X_FORWARDED_FOR', request.remote_addr or '')
            user_agent = request.headers.get('User-Agent', '')
        except Exception:
            pass

    try:
        AuditLog.log(
            event_type=event_type,
            user_uid=user_uid or "",
            client_id=client_id or "",
            ip_address=ip_address,
            user_agent=user_agent,
            metadata=metadata or {},
        )
    except Exception as e:
        print(f'audit_service: failed to log event {event_type}: {e}')
