use night_fury_core::BrowserSession;
use serde_json::json;

use night_fury_cli_core::output::{output_err, output_ok, OutputMode};

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub(super) enum ClipboardSub {
    Read,
    Write,
    Unknown,
}

pub(super) fn resolve_clipboard_sub(s: &str) -> ClipboardSub {
    match s {
        "read" => ClipboardSub::Read,
        "write" => ClipboardSub::Write,
        _ => ClipboardSub::Unknown,
    }
}

pub async fn dispatch(session: &BrowserSession, parts: &[&str], mode: OutputMode) {
    let sub = parts.first().copied().unwrap_or("");
    match resolve_clipboard_sub(sub) {
        ClipboardSub::Read => read(session, mode).await,
        ClipboardSub::Write => write(session, &parts[1..], mode).await,
        ClipboardSub::Unknown => output_err(
            mode,
            &format!("Unknown clipboard subcommand: {sub}. Use 'read' or 'write <text>'"),
        ),
    }
}

async fn read(session: &BrowserSession, mode: OutputMode) {
    match session.clipboard_read().await {
        Ok(text) => output_ok(mode, &text, json!({"text": text})),
        Err(e) => output_err(mode, &e.to_string()),
    }
}

async fn write(session: &BrowserSession, parts: &[&str], mode: OutputMode) {
    let text = parts.join(" ");
    if text.is_empty() {
        output_err(mode, "Usage: clipboard write <text>");
        return;
    }
    match session.clipboard_write(&text).await {
        Ok(msg) => output_ok(
            mode,
            &msg,
            json!({"action": "clipboard_write", "text": text}),
        ),
        Err(e) => output_err(mode, &e.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use super::{resolve_clipboard_sub, ClipboardSub};

    #[test]
    fn resolves_known_subcommands() {
        assert_eq!(resolve_clipboard_sub("read"), ClipboardSub::Read);
        assert_eq!(resolve_clipboard_sub("write"), ClipboardSub::Write);
    }

    #[test]
    fn unknown_subcommand_returns_unknown() {
        assert_eq!(resolve_clipboard_sub(""), ClipboardSub::Unknown);
        assert_eq!(resolve_clipboard_sub("copy"), ClipboardSub::Unknown);
    }
}
