//! Logging handler — logging/setLevel

use serde_json::Value;

use crate::protocol::errors::McpError;
use crate::protocol::types::JsonRpcResponse;
use crate::server::core::Server;
use crate::server::handler::{RequestContext, error_response, success_response};

impl Server {
    /// Handle logging/setLevel request
    pub(crate) async fn handle_logging_set_level(&self, ctx: RequestContext) -> JsonRpcResponse {
        use crate::logging::LogLevel;
        use crate::protocol::types::SetLevelRequest;

        // Parse request params
        let params = ctx.params().cloned().unwrap_or(Value::Null);
        let req: SetLevelRequest = match serde_json::from_value(params) {
            Ok(req) => req,
            Err(_) => {
                return error_response(
                    ctx.request.id,
                    McpError::validation("invalid_params", "Invalid setLevel parameters")
                        .to_jsonrpc(),
                );
            }
        };

        // Parse log level
        let level = match req.level.parse::<LogLevel>() {
            Ok(level) => level,
            Err(_) => {
                return error_response(
                    ctx.request.id,
                    McpError::validation(
                        "invalid_level",
                        format!(
                            "Invalid log level '{}'. Valid levels: debug, info, notice, warning, error, critical, alert, emergency",
                            req.level
                        ),
                    )
                    .to_jsonrpc(),
                )
            }
        };

        // Update logger min level
        self.logger.set_min_level(level);

        tracing::debug!(level = %req.level, "Log level updated");

        success_response(ctx.request.id, serde_json::json!({}))
    }
}
