//! Demo: multiple RPC calls against a running Knafeh server.
//!
//! Start the server first:  cargo run --no-default-features --example rust_server
//! Then run this:           cargo run --no-default-features --example rust_client_demo

use knafeh::client::Client;
use knafeh::transport::tls::TlsConfig;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt::init();

    let client = Client::builder()
        .endpoint("localhost:4433")
        .tls(TlsConfig::client_insecure())
        .build()
        .await?;

    // 1. say_hello
    let body = serde_json::to_vec(&serde_json::json!({ "name": "Knafeh" }))?;
    let resp = client.call("greeter/say_hello", body).await?;
    let val: serde_json::Value = serde_json::from_slice(&resp.body)?;
    println!("[say_hello]  status={:?}  body={}", resp.status.code, val);

    // 2. say_goodbye
    let body = serde_json::to_vec(&serde_json::json!({ "name": "World" }))?;
    let resp = client.call("greeter/say_goodbye", body).await?;
    let val: serde_json::Value = serde_json::from_slice(&resp.body)?;
    println!("[say_goodbye] status={:?}  body={}", resp.status.code, val);

    // 3. method not found
    let resp = client.call("greeter/unknown", br#"{}"#.to_vec()).await?;
    println!(
        "[unknown]    status={:?}  message={:?}",
        resp.status.code, resp.status.message
    );

    // 4. service not found
    let resp = client.call("nope/method", br#"{}"#.to_vec()).await?;
    println!(
        "[nope/method] status={:?}  message={:?}",
        resp.status.code, resp.status.message
    );

    // 5. connection reuse
    println!("\nPool connections: {}", client.pool().size());

    Ok(())
}
