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

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

pub async fn go(session: &BrowserSession, parts: &[&str], mode: OutputMode) {
    let url = parts.first().copied().unwrap_or("").trim();
    if url.is_empty() {
        output_err(mode, "Usage: go <url>");
        return;
    }
    match session.navigate(url).await {
        Ok(msg) => output_ok(mode, &msg, json!({"url": url})),
        Err(e) => output_err(mode, &e.to_string()),
    }
}

pub async fn back(session: &BrowserSession, mode: OutputMode) {
    match session.back().await {
        Ok(msg) => output_ok(mode, &msg, json!({"action": "back"})),
        Err(e) => output_err(mode, &e.to_string()),
    }
}

pub async fn forward(session: &BrowserSession, mode: OutputMode) {
    match session.forward().await {
        Ok(msg) => output_ok(mode, &msg, json!({"action": "forward"})),
        Err(e) => output_err(mode, &e.to_string()),
    }
}

pub async fn reload(session: &BrowserSession, mode: OutputMode) {
    match session.reload().await {
        Ok(msg) => output_ok(mode, &msg, json!({"action": "reload"})),
        Err(e) => output_err(mode, &e.to_string()),
    }
}

pub async fn url(session: &BrowserSession, mode: OutputMode) {
    match session.get_url().await {
        Ok(u) => output_ok(mode, &u, json!({"url": u})),
        Err(e) => output_err(mode, &e.to_string()),
    }
}

pub async fn title(session: &BrowserSession, mode: OutputMode) {
    match session.get_title().await {
        Ok(t) => output_ok(mode, &t, json!({"title": t})),
        Err(e) => output_err(mode, &e.to_string()),
    }
}
