use crate::channels::manager::ChannelManager;
use crate::command::context::CommandContext;
use crate::command::handler::{CommandHandler, CommandMetadata};
use crate::command::response::{CommandError, CommandResponse, MessageKind};
use crate::command::Command;
use async_trait::async_trait;
use std::sync::Arc;

/// 列出通道命令处理器
pub struct ListChannelsCommandHandler {
    channel_manager: Arc<ChannelManager>,
}

impl ListChannelsCommandHandler {
    pub fn new(channel_manager: Arc<ChannelManager>) -> Self {
        Self { channel_manager }
    }
}

#[async_trait]
impl CommandHandler for ListChannelsCommandHandler {
    fn can_handle(&self, cmd: &Command) -> bool {
        matches!(cmd, Command::ListChannels)
    }

    fn metadata(&self) -> Option<CommandMetadata> {
        Some(CommandMetadata {
            name: "channels",
            description: "列出所有可用通道",
            usage: "/channels",
        })
    }

    async fn handle(
        &self,
        cmd: Command,
        ctx: CommandContext,
    ) -> Result<CommandResponse, CommandError> {
        match cmd {
            Command::ListChannels => handle_list_channels(self, ctx).await,
            _ => unreachable!(),
        }
    }
}

async fn handle_list_channels(
    handler: &ListChannelsCommandHandler,
    ctx: CommandContext,
) -> Result<CommandResponse, CommandError> {
    let channels = handler.channel_manager.build_channel_list().await;

    let channels_json = serde_json::to_string(&channels)
        .map_err(|e| CommandError::new("SERIALIZE_ERROR", e.to_string()))?;

    let message = format!("Available channels: {}", channels.len());

    Ok(CommandResponse::success(ctx.request_id)
        .with_message(MessageKind::Notification, &message)
        .with_metadata("channels", &channels_json)
        .with_metadata("count", &channels.len().to_string()))
}
