# Shared helpers for NATS admin lib:
# subject builder, credential resolution, and the low-level request wrapper.

# Resolve the NATS server URL.  CLI flag takes precedence over env, env over default.
export def nats-admin-url [override: string = ""] {
    if ($override | is-not-empty) {
        $override
    } else {
        $env.NATS_ADMIN_URL? | default "nats://localhost:4222"
    }
}

# Resolve the NATS credentials file path.
export def nats-admin-creds [override: string = ""] {
    if ($override | is-not-empty) {
        $override
    } else {
        $env.NATS_ADMIN_CREDS? | default ""
    }
}

# Build a full NATS subject from the configured namespace and a leaf name.
#
# Subject pattern: `{prefix}.{env}.{leaf}`
# Driven by NATS_ADMIN_NAMESPACE_PREFIX and NATS_ADMIN_NAMESPACE_ENV (same env
# vars used by the Rust server at startup).
#
# Examples:
#   (build-admin-subject "admin.health")  → "evol.website.prod.admin.health"
export def build-admin-subject [leaf: string] {
    let prefix = $env.NATS_ADMIN_NAMESPACE_PREFIX? | default "rustelo"
    let env_name = $env.NATS_ADMIN_NAMESPACE_ENV? | default "local"
    $"($prefix).($env_name).($leaf)"
}

# Send a request-reply to a NATS subject and return the raw response string.
#
# Wraps `nats request` CLI.  Credentials file is optional.
# Timeout defaults to 5 s; override via `--timeout`.
export def nats-admin-request [
    subject:  string         # Full subject string
    payload:  string = "{}"  # JSON payload (default empty object)
    --url:    string = ""    # NATS server URL override
    --creds:  string = ""    # Credentials file override
    --timeout: string = "5s" # Request timeout (nats CLI format e.g. 5s, 30s)
] {
    let server = nats-admin-url $url
    let creds_path = nats-admin-creds $creds

    let base = ["request", "--server", $server, "--timeout", $timeout, $subject, $payload]

    let args = if ($creds_path | is-not-empty) {
        ["--creds", $creds_path] ++ $base
    } else {
        $base
    }

    ^nats ...$args | str trim
}
