//! Volume domain tools — list and show Hetzner Cloud volumes.

use crate::protocol::{ToolCategory, ToolError};
use crate::providers::hcloud::HcloudClient;
use crate::tool::{Context, Tool};
use async_trait::async_trait;
use serde_json::{Value, json};
use std::sync::Arc;

// ── volume_list ───────────────────────────────────────────────────────────────

pub struct VolumeList {
    hcloud: Arc<HcloudClient>,
}
impl VolumeList {
    pub fn new(hcloud: Arc<HcloudClient>) -> Self { Self { hcloud } }
}

#[async_trait]
impl Tool for VolumeList {
    fn name(&self) -> &'static str { "volume_list" }
    fn description(&self) -> &'static str { "List all Hetzner Cloud volumes in the active context" }
    fn schema(&self) -> Value {
        json!({ "type": "object", "properties": {} })
    }
    fn category(&self) -> ToolCategory { ToolCategory::Read }

    async fn invoke(&self, _params: Value, _ctx: &Context) -> Result<Value, ToolError> {
        let volumes = self.hcloud.volume_list().await?;
        let items = volumes.as_array().cloned().unwrap_or_default();
        Ok(json!({ "items": items, "total": items.len() }))
    }
}

// ── volume_show ───────────────────────────────────────────────────────────────

pub struct VolumeShow {
    hcloud: Arc<HcloudClient>,
}
impl VolumeShow {
    pub fn new(hcloud: Arc<HcloudClient>) -> Self { Self { hcloud } }
}

#[async_trait]
impl Tool for VolumeShow {
    fn name(&self) -> &'static str { "volume_show" }
    fn description(&self) -> &'static str { "Show details of a specific Hetzner Cloud volume" }
    fn schema(&self) -> Value {
        json!({
            "type": "object",
            "required": ["name"],
            "properties": {
                "name": { "type": "string", "description": "Volume name or ID" }
            }
        })
    }
    fn category(&self) -> ToolCategory { ToolCategory::Read }

    async fn invoke(&self, params: Value, _ctx: &Context) -> Result<Value, ToolError> {
        let name = params["name"]
            .as_str()
            .ok_or_else(|| ToolError::invalid_param("name", "required string"))?;
        self.hcloud.volume_describe(name).await
    }
}
