# Health check commands for the NATS admin bus.
#
# Requires a running Rustelo server with `nats-admin` feature enabled and
# `external_services.nats_admin.enabled = true`.

use ./common.nu [build-admin-subject, nats-admin-request]

# Send a health-check request and return a structured record.
#
# Response shape: { status: string, host: string, version: string }
#
# Examples:
#   nats-admin health
#   nats-admin health --url nats://nats-hub:4222 --creds /etc/nats/admin.creds
export def "nats-admin health" [
    --url:   string = "" # NATS server URL (overrides NATS_ADMIN_URL)
    --creds: string = "" # Credentials file (overrides NATS_ADMIN_CREDS)
] {
    let subject = build-admin-subject "admin.health"
    nats-admin-request $subject --url $url --creds $creds | from json
}

# Check health and exit non-zero if the server reports anything other than "ok".
#
# Suitable for use in CI / k8s liveness probes:
#   nats-admin health check && echo "healthy"
export def "nats-admin health check" [
    --url:   string = ""
    --creds: string = ""
] {
    let result = nats-admin health --url $url --creds $creds
    let status = $result.status? | default "unknown"

    if $status != "ok" {
        error make { msg: $"Health check failed — status: ($status)" }
    }
}

# Print a formatted health summary table.
export def "nats-admin health show" [
    --url:   string = ""
    --creds: string = ""
] {
    nats-admin health --url $url --creds $creds
        | transpose key value
        | print
}
