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

use super::{common, ToolResult};

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RequestKeyParams {
    pub key_name: String,
    #[serde(default)]
    pub description: String,
}

pub async fn execute(params: RequestKeyParams) -> ToolResult {
    common::validate_secret_name(&params.key_name, "key_name")?;
    common::validate_bounded_string(
        &params.description,
        "description",
        common::MAX_STRING_LENGTH,
    )?;
    let signals = envseal::ops::request_key(&params.key_name, &params.description)
        .map_err(|e| e.to_string())?;

    let entropy_warnings: Vec<_> = signals
        .iter()
        .map(|s| {
            json!({
                "id": s.id.as_str(),
                "category": s.category.as_str(),
                "severity": s.severity.as_str(),
                "label": s.label,
                "detail": s.detail,
                "mitigation": s.mitigation,
            })
        })
        .collect();

    Ok(json!({
        "stored": true,
        "key_name": params.key_name,
        "entropy_warnings": entropy_warnings,
    }))
}
