//! PostgreSQL Cluster Deployment Example
//!
//! This example shows how to deploy a PostgreSQL cluster using the
//! KubernetesManager convenience methods.

use herolib_system::kubernetes::KubernetesManager;
use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create Kubernetes manager for the database namespace
    let km = KubernetesManager::new("database").await?;

    // Create the namespace if it doesn't exist
    println!("Creating namespace 'database' if it doesn't exist...");
    match km.namespace_create("database").await {
        Ok(_) => println!("✓ Namespace 'database' created"),
        Err(e) => {
            if e.to_string().contains("already exists") {
                println!("✓ Namespace 'database' already exists");
            } else {
                return Err(e.into());
            }
        }
    }

    // Clean up any existing resources first
    println!("Cleaning up any existing PostgreSQL resources...");
    match km.deployment_delete("postgres-cluster").await {
        Ok(_) => println!("✓ Deleted existing deployment"),
        Err(_) => println!("✓ No existing deployment to delete"),
    }

    match km.service_delete("postgres-cluster").await {
        Ok(_) => println!("✓ Deleted existing service"),
        Err(_) => println!("✓ No existing service to delete"),
    }

    // Configure PostgreSQL-specific labels
    let mut labels = HashMap::new();
    labels.insert("app".to_string(), "postgres-cluster".to_string());
    labels.insert("type".to_string(), "database".to_string());
    labels.insert("engine".to_string(), "postgresql".to_string());

    // Configure PostgreSQL environment variables
    let mut env_vars = HashMap::new();
    env_vars.insert("POSTGRES_DB".to_string(), "myapp".to_string());
    env_vars.insert("POSTGRES_USER".to_string(), "postgres".to_string());
    env_vars.insert(
        "POSTGRES_PASSWORD".to_string(),
        "secretpassword".to_string(),
    );
    env_vars.insert(
        "PGDATA".to_string(),
        "/var/lib/postgresql/data/pgdata".to_string(),
    );

    // Deploy the PostgreSQL cluster using the convenience method
    println!("Deploying PostgreSQL cluster...");
    km.deploy_application(
        "postgres-cluster", // name
        "postgres:15",      // image
        2,                  // replicas (1 master + 1 replica)
        5432,               // port
        Some(labels),       // labels
        Some(env_vars),     // environment variables
    )
    .await?;

    println!("✅ PostgreSQL cluster deployed successfully!");

    // Check deployment status
    let deployments = km.deployments_list().await?;
    let postgres_deployment = deployments
        .iter()
        .find(|d| d.metadata.name.as_ref() == Some(&"postgres-cluster".to_string()));

    if let Some(deployment) = postgres_deployment {
        let total_replicas = deployment
            .spec
            .as_ref()
            .and_then(|s| s.replicas)
            .unwrap_or(0);
        let ready_replicas = deployment
            .status
            .as_ref()
            .and_then(|s| s.ready_replicas)
            .unwrap_or(0);

        println!(
            "Deployment status: {}/{} replicas ready",
            ready_replicas, total_replicas
        );
    }

    println!("\n📋 Connection Information:");
    println!("  Host: postgres-cluster.database.svc.cluster.local");
    println!("  Port: 5432");
    println!("  Database: postgres (default)");
    println!("  Username: postgres (default)");
    println!("  Password: Set POSTGRES_PASSWORD environment variable");

    println!("\n🔧 To connect from another pod:");
    println!("  psql -h postgres-cluster.database.svc.cluster.local -U postgres");

    println!("\n💡 Next steps:");
    println!("  • Set environment variables for database credentials");
    println!("  • Add persistent volume claims for data storage");
    println!("  • Configure backup and monitoring");

    Ok(())
}
