use crate::command::context::CommandContext;
use crate::command::handler::{CommandHandler, CommandMetadata};
use crate::command::response::{CommandError, CommandResponse};
use crate::command::Command;
use async_trait::async_trait;

/// 加载指定 channel + chat_id 的对话消息。
/// 实际的消息加载和发送在 ws.rs 中处理（类似 send_task_messages）。
/// 此 handler 仅验证参数并通过 metadata 传递 chat_id。
pub struct LoadChatMessagesCommandHandler;

impl LoadChatMessagesCommandHandler {
    pub fn new() -> Self {
        Self
    }
}

impl Default for LoadChatMessagesCommandHandler {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn metadata(&self) -> Option<CommandMetadata> {
        Some(CommandMetadata {
            name: "load_chat_messages",
            description: "加载指定 channel 和 chat_id 的对话消息",
            usage: "/load_chat_messages <channel> <chat_id>",
        })
    }

    async fn handle(
        &self,
        cmd: Command,
        ctx: CommandContext,
    ) -> Result<CommandResponse, CommandError> {
        match cmd {
            Command::LoadChatMessages { channel, chat_id } => {
                if channel.is_empty() {
                    return Err(CommandError::new(
                        "INVALID_ARGUMENT",
                        "channel must not be empty".to_string(),
                    ));
                }
                if chat_id.is_empty() {
                    return Err(CommandError::new(
                        "INVALID_ARGUMENT",
                        "chat_id must not be empty".to_string(),
                    ));
                }

                Ok(CommandResponse::success(ctx.request_id)
                    .with_metadata("load_chat_channel", &channel)
                    .with_metadata("load_chat_id", &chat_id))
            }
            _ => unreachable!(),
        }
    }
}
