use serde::Deserialize;
use serde_json::json;

use super::ToolResult;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuditParams {
    #[serde(default = "default_limit")]
    pub limit: usize,
    /// Case-insensitive substring search across all fields (secret
    /// names, binary paths, signal IDs, event types, etc.).
    pub query: Option<String>,
    /// Restrict to a specific event type tag. Examples:
    /// `secret_stored`, `approval_result`, `signal_recorded`,
    /// `secret_revoked`, `secret_accessed`, `tier_changed`.
    pub event_type: Option<String>,
}

fn default_limit() -> usize {
    20
}

pub async fn execute(params: AuditParams) -> ToolResult {
    let limit = params.limit.clamp(1, 500);
    let filter = envseal::audit::AuditFilter {
        query: params.query.filter(|s| !s.is_empty()),
        event_type: params.event_type.filter(|s| !s.is_empty()),
    };
    let entries = envseal::ops::audit_log_filtered(limit, &filter);
    Ok(json!({
        "count": entries.len(),
        "filter": {
            "query": filter.query,
            "event_type": filter.event_type,
        },
        "entries": entries
    }))
}
