//! Example: Using the health-aware Supabase client
//!
//! This example demonstrates how to use the HealthAwareSupabaseClient
//! with automatic health tracking and circuit breaking.
//!
//! Run with:
//! ```bash
//! cargo run --example supabase_health_tracking
//! ```

use athena_rs::drivers::supabase::client::{HealthAwareSupabaseClient, SupabaseConnectionInfo};
use serde_json::json;
use std::error::Error;

use std::time::{Duration, Instant};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Initialize tracing for logging
    tracing_subscriber::fmt().with_env_filter("info").init();

    println!("Health-Aware Supabase Client Example\n");

    // Create a connection info from environment variables
    let info: SupabaseConnectionInfo =
        SupabaseConnectionInfo::from_env("SUPABASE_URL", "SUPABASE_KEY")?;

    println!("Connecting to: {}", info.host);
    println!("   URL: {}\n", info.url);

    // Create the health-aware client
    let athena: HealthAwareSupabaseClient = HealthAwareSupabaseClient::new(info)?;

    // Example 1: Basic SELECT query
    println!("Example 1: Basic SELECT query");
    match athena
        .select("users")
        .columns(vec!["id", "email", "created_at"])
        .limit(5)
        .execute()
        .await
    {
        Ok(results) => {
            println!(" Query succeeded! Got {} rows", results.len());
            for (i, row) in results.iter().enumerate().take(3) {
                println!("Row {}: {}", i + 1, row);
            }
        }
        Err(e) => println!("Query failed: {}", e),
    }

    println!();

    // Example 2: Query with filters
    println!("Example 2: Query with filters");
    match athena
        .select("users")
        .columns(vec!["id", "email"])
        .eq("status", "active")
        .order("created_at", false)
        .limit(10)
        .execute()
        .await
    {
        Ok(results) => println!("Filtered query succeeded! Got {} rows", results.len()),
        Err(e) => println!("Query failed: {}", e),
    }

    println!();

    // Example 3: Insert data
    println!("Example 3: Insert data");
    let new_user = json!({
        "email": "test@example.com",
        "name": "Test User",
        "status": "active"
    });

    match athena.insert("users", new_user).await {
        Ok(id) => println!("Insert succeeded! New ID: {}", id),
        Err(e) => println!("Insert failed: {}", e),
    }

    println!();

    // Example 4: Check health status
    println!("Example 4: Health status check");
    if let Some(offline_until) = athena.is_offline() {
        println!("Host is currently offline until: {:?}", offline_until);
    } else {
        println!("Host is healthy and available");
    }

    println!();

    // Example 5: Manual circuit breaking (for testing)
    println!("Example 5: Manual circuit breaking");
    println!("Forcing host offline for 10 seconds...");
    let deadline: Instant = athena.force_offline(Duration::from_secs(10));
    println!("   Host will be offline until: {:?}", deadline);

    // Try to query while offline
    match athena.select("users").limit(1).execute().await {
        Ok(_) => println!("Unexpected success - should be offline!"),
        Err(e) => println!("Correctly blocked: {}", e),
    }

    println!();

    // Example 6: Reset health tracking
    println!("Example 6: Reset health tracking");
    athena.reset_health();
    println!("Health tracking reset - host is available again");

    // Verify we can query again
    match athena.select("users").limit(1).execute().await {
        Ok(results) => println!("Query after reset succeeded! Got {} rows", results.len()),
        Err(e) => println!("Query failed: {}", e),
    }

    println!("Example completed!");

    Ok(())
}
