//! Discord conversation history persistence.

use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex as TokioMutex;

use crate::chat::history::{load_chat_history, save_chat_history};
use crate::chat::transport::matrix::RoomConversation;

/// Per-channel conversation history, keyed by channel ID.
pub type DiscordConversationHistory = Arc<TokioMutex<HashMap<String, RoomConversation>>>;

/// Path to the persisted Discord conversation history file.
const DISCORD_HISTORY_FILE: &str = ".huskies/discord_history.json";

/// Load Discord conversation history from disk.
pub fn load_discord_history(project_root: &std::path::Path) -> HashMap<String, RoomConversation> {
    load_chat_history(project_root, DISCORD_HISTORY_FILE, "discord")
}

/// Save Discord conversation history to disk.
pub(super) fn save_discord_history(
    project_root: &std::path::Path,
    history: &HashMap<String, RoomConversation>,
) {
    save_chat_history(project_root, DISCORD_HISTORY_FILE, "discord", history);
}

// ── Tests ───────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chat::transport::matrix::{ConversationEntry, ConversationRole};

    #[test]
    fn save_and_load_discord_history_round_trips() {
        let tmp = tempfile::tempdir().unwrap();
        let sk = tmp.path().join(".huskies");
        std::fs::create_dir_all(&sk).unwrap();

        let mut history = HashMap::new();
        history.insert(
            "123456789".to_string(),
            RoomConversation {
                session_id: Some("sess-abc".to_string()),
                entries: vec![
                    ConversationEntry {
                        role: ConversationRole::User,
                        sender: "user123".to_string(),
                        content: "hello".to_string(),
                    },
                    ConversationEntry {
                        role: ConversationRole::Assistant,
                        sender: String::new(),
                        content: "hi there!".to_string(),
                    },
                ],
                ..Default::default()
            },
        );

        save_discord_history(tmp.path(), &history);
        let loaded = load_discord_history(tmp.path());

        assert_eq!(loaded.len(), 1);
        let conv = loaded.get("123456789").unwrap();
        assert_eq!(conv.session_id.as_deref(), Some("sess-abc"));
        assert_eq!(conv.entries.len(), 2);
        assert_eq!(conv.entries[0].content, "hello");
        assert_eq!(conv.entries[1].content, "hi there!");
    }

    #[test]
    fn load_discord_history_returns_empty_when_file_missing() {
        let tmp = tempfile::tempdir().unwrap();
        let history = load_discord_history(tmp.path());
        assert!(history.is_empty());
    }

    #[test]
    fn load_discord_history_returns_empty_on_invalid_json() {
        let tmp = tempfile::tempdir().unwrap();
        let sk = tmp.path().join(".huskies");
        std::fs::create_dir_all(&sk).unwrap();
        std::fs::write(sk.join("discord_history.json"), "not json {{{").unwrap();
        let history = load_discord_history(tmp.path());
        assert!(history.is_empty());
    }
}
