use anyhow::Result;
use cloud::client::auth::load_token;

pub fn handle() -> Result<()> {
    // If authenticated, open the web dashboard pre-logged in
    if let Some(token) = load_token() {
        let base = token.endpoint.trim_end_matches('/');
        // JWT contains +, /, = which are URL-special — percent-encode them
        let encoded = token
            .access_token
            .replace('+', "%2B")
            .replace('/', "%2F")
            .replace('=', "%3D");
        let url = format!("{base}/?token={encoded}");
        println!("Opening dashboard at {base}/");
        if open::that(&url).is_err() {
            println!("Could not open browser. Visit:");
            println!("  {url}");
        }
        return Ok(());
    }

    // Not logged in — open dashboard login page
    let url = "https://api.betterctx.com/";
    println!("Not logged in. Run `bctx login` first, or open the dashboard manually:");
    println!("  {url}");
    let _ = open::that(url);
    Ok(())
}
