use std::path::Path;

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

use super::{common, ToolResult};

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ListParams {
    pub filter: Option<String>,
}

pub async fn execute(params: ListParams) -> ToolResult {
    let root = envseal::ops::vault_root().map_err(|_| "unable to locate vault root".to_string())?;

    let mut names = envseal::ops::list_secret_names(Path::new(&root)).map_err(|e| e.to_string())?;

    if let Some(filter) = params.filter {
        common::validate_bounded_string(&filter, "filter", common::MAX_STRING_LENGTH)?;
        let lower = filter.to_lowercase();
        names.retain(|name| name.to_lowercase().contains(&lower));
    }

    Ok(json!({
        "count": names.len(),
        "secrets": names,
    }))
}
