//! List all symbols for a demo account, then verify XAUUSD exists.
//!
//! Usage:
//!   cargo run --example symbols_list

use std::time::Duration;

use ctrader_rs::{Client, Config};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenvy::dotenv().ok();

    tracing_subscriber::fmt()
        .with_env_filter("symbols_list=debug,ctrader_rs=debug")
        .with_line_number(true)
        .init();

    let client_id = std::env::var("CTRADER_CLIENT_ID")?;
    let secret = std::env::var("CTRADER_SECRET")?;
    let token = std::env::var("CTRADER_TOKEN")?;
    let account_id: i64 = std::env::var("CTRADER_ACCOUNT_ID")?.parse()?;

    let config = Config::new(client_id, secret).deadline(Duration::from_secs(5));

    println!("Connecting …");
    let client = Client::start(config).await?;
    println!("✓ Connected");

    // Authenticate the account
    let auth_res = client.account_auth(account_id, &token).await?;
    assert_eq!(auth_res.ctid_trader_account_id, account_id);
    println!("✓ Account {account_id} authenticated");

    // Fetch symbol list
    let res = client.symbols_list(account_id, false).await?;
    println!("\nTotal symbols: {}", res.symbol.len());

    // Verify XAUUSD is present (same assertion as the Go test)
    let xauusd = res
        .symbol
        .iter()
        .find(|s| s.symbol_name.as_deref() == Some("XAUUSD"));

    match xauusd {
        Some(sym) => println!(
            "✓ XAUUSD found  (id={}, enabled={})",
            sym.symbol_id,
            sym.enabled.unwrap_or(false)
        ),
        None => println!("✗ XAUUSD NOT found in symbol list"),
    }

    // Print first 10 symbols
    println!("\nFirst 10 symbols:");
    println!("{:<10} {:<15} {}", "ID", "Name", "Enabled");
    println!("{}", "-".repeat(35));
    for sym in res.symbol.iter().take(10) {
        println!(
            "{:<10} {:<15} {}",
            sym.symbol_id,
            sym.symbol_name.as_deref().unwrap_or(""),
            sym.enabled.unwrap_or(false),
        );
    }

    Ok(())
}
