use std::sync::Arc;

use crate::agent::AgentError;
use crate::storage::{SessionRecord, SessionStore};

#[derive(Clone)]
pub(crate) struct CliSessionService {
    store: Arc<SessionStore>,
}

impl CliSessionService {
    pub(crate) fn new(store: Arc<SessionStore>) -> Self {
        Self { store }
    }

    pub(crate) fn create(&self, title: Option<&str>) -> Result<SessionRecord, AgentError> {
        self.store
            .create_cli_session(title)
            .map_err(|err| AgentError::Other(format!("create session error: {}", err)))
    }

    /// 创建指定通道的会话
    #[allow(dead_code)]
    pub(crate) fn create_with_channel(
        &self,
        channel_name: &str,
        title: Option<&str>,
    ) -> Result<SessionRecord, AgentError> {
        self.store
            .create_session(channel_name, title)
            .map_err(|err| AgentError::Other(format!("create session error: {}", err)))
    }

    #[allow(dead_code)]
    pub(crate) fn get(&self, session_id: &str) -> Result<Option<SessionRecord>, AgentError> {
        self.store
            .get_session(session_id)
            .map_err(|err| AgentError::Other(format!("get session error: {}", err)))
    }

    #[allow(dead_code)]
    pub(crate) fn list(&self, include_archived: bool) -> Result<Vec<SessionRecord>, AgentError> {
        self.store
            .list_sessions("cli", include_archived)
            .map_err(|err| AgentError::Other(format!("list sessions error: {}", err)))
    }

    /// 列出指定通道的会话
    #[allow(dead_code)]
    pub(crate) fn list_by_channel(
        &self,
        channel_name: &str,
        include_archived: bool,
    ) -> Result<Vec<SessionRecord>, AgentError> {
        self.store
            .list_sessions(channel_name, include_archived)
            .map_err(|err| AgentError::Other(format!("list sessions error: {}", err)))
    }

    #[allow(dead_code)]
    pub(crate) fn rename(&self, session_id: &str, title: &str) -> Result<(), AgentError> {
        self.store
            .rename_session(session_id, title)
            .map_err(|err| AgentError::Other(format!("rename session error: {}", err)))
    }

    #[allow(dead_code)]
    pub(crate) fn archive(&self, session_id: &str) -> Result<(), AgentError> {
        self.store
            .archive_session(session_id)
            .map_err(|err| AgentError::Other(format!("archive session error: {}", err)))
    }

    #[allow(dead_code)]
    pub(crate) fn delete(&self, session_id: &str) -> Result<(), AgentError> {
        self.store
            .delete_session(session_id)
            .map_err(|err| AgentError::Other(format!("delete session error: {}", err)))
    }

    #[allow(dead_code)]
    pub(crate) fn clear_messages(&self, session_id: &str) -> Result<(), AgentError> {
        self.store
            .clear_messages(session_id)
            .map_err(|err| AgentError::Other(format!("clear session error: {}", err)))
    }
}
