#!/usr/bin/env herodo
// Pre-flight check: Ensure Kubernetes cluster is accessible
try {
    if !run("kubectl cluster-info").execute().success {
        print("SKIPPED: Kubernetes cluster is not accessible");
        exit(0);
    }
} catch(e) {
    print("SKIPPED: Kubernetes cluster is not accessible: " + e);
    exit(0);
}

//! PostgreSQL Cluster Deployment Example (Rhai)
//!
//! This script shows how to deploy a PostgreSQL cluster using Rhai scripting
//! with the KubernetesManager convenience methods.

print("=== PostgreSQL Cluster Deployment ===");

// Create Kubernetes manager for the database namespace
print("Creating Kubernetes manager for 'database' namespace...");
let km = kubernetes("database");
print("✓ Kubernetes manager created");

// Create the namespace if it doesn't exist
print("Creating namespace 'database' if it doesn't exist...");
try {
    create_namespace(km, "database");
    print("✓ Namespace 'database' created");
} catch(e) {
    if e.to_string().contains("already exists") {
        print("✓ Namespace 'database' already exists");
    } else {
        print("⚠️ Warning: " + e);
    }
}

// Clean up any existing resources first
print("\nCleaning up any existing PostgreSQL resources...");
try {
    delete_deployment(km, "postgres-cluster");
    print("✓ Deleted existing deployment");
} catch(e) {
    print("✓ No existing deployment to delete");
}

try {
    delete_service(km, "postgres-cluster");
    print("✓ Deleted existing service");
} catch(e) {
    print("✓ No existing service to delete");
}

// Create PostgreSQL cluster using the convenience method
print("\nDeploying PostgreSQL cluster...");

try {
    // Deploy PostgreSQL using the convenience method
    let result = deploy_application(km, "postgres-cluster", "postgres:15", 2, 5432, #{
        "app": "postgres-cluster",
        "type": "database",
        "engine": "postgresql"
    }, #{
        "POSTGRES_DB": "myapp",
        "POSTGRES_USER": "postgres",
        "POSTGRES_PASSWORD": "secretpassword",
        "PGDATA": "/var/lib/postgresql/data/pgdata"
    });
    print("✓ " + result);

    print("\n✅ PostgreSQL cluster deployed successfully!");

    print("\n📋 Connection Information:");
    print("  Host: postgres-cluster.database.svc.cluster.local");
    print("  Port: 5432");
    print("  Database: postgres (default)");
    print("  Username: postgres (default)");

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

    print("\n💡 Next steps:");
    print("  • Set POSTGRES_PASSWORD environment variable");
    print("  • Configure persistent storage");
    print("  • Set up backup and monitoring");

} catch(e) {
    print("❌ Failed to deploy PostgreSQL cluster: " + e);
}

print("\n=== Deployment Complete ===");
