//! `POST /api/audit/conn` — fire-and-forget connection log entry. The client
//! ([src/server/connection.rs:1248-1279](file:///Users/sn0/Desktop/rustdesk/src/server/connection.rs#L1248))
//! emits this on every accepted session, no Authorization header. We answer
//! with `{"guid":"..."}` so the client can pass that guid back later in
//! `PUT /api/audit` (CONSOLE_API.md §7.1).

use crate::api::error::ApiError;
use crate::api::state::AppState;
use axum::extract::Extension;
use axum::Json;
use serde::Deserialize;
use serde_json::{json, Value};
use std::sync::Arc;

#[derive(Debug, Deserialize)]
pub struct ConnAuditBody {
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub uuid: String,
    #[serde(default)]
    pub conn_id: i64,
    #[serde(default)]
    pub session_id: i64,
    #[serde(default)]
    pub ip: String,
    #[serde(default)]
    pub action: String,
}

pub async fn conn(
    Extension(state): Extension<Arc<AppState>>,
    Json(body): Json<ConnAuditBody>,
) -> Result<Json<Value>, ApiError> {
    if body.id.is_empty() {
        return Err(ApiError::BadRequest("id required".into()));
    }
    let action = if body.action.is_empty() {
        "new"
    } else {
        body.action.as_str()
    };
    let guid = state
        .db
        .audit_conn_insert(&body.id, body.conn_id, body.session_id, &body.ip, action)
        .await
        .map_err(|e| ApiError::Internal(e.to_string()))?;
    Ok(Json(json!({ "guid": guid })))
}
