# Website-specific NATS ops commands.
#
# These publish fire-and-forget signals on the `ops.*` subjects consumed by
# CI/CD listeners and the server's config-reload watcher.

use {{RUSTELO_ROOT}}/admin/lib/common.nu [build-admin-subject, nats-admin-url, nats-admin-creds]

# Internal: fire-and-forget publish (no reply expected).
def nats-pub [
    subject: string
    payload: string
    --url:   string = ""
    --creds: string = ""
] {
    let server = nats-admin-url $url
    let creds_path = nats-admin-creds $creds

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

    ^nats ...$args
}

# Publish a deploy signal to the ops bus.
#
# CI/CD calls this after a successful build to notify running supervisors or
# monitoring tooling.  The server does NOT restart automatically; this is a
# signal only.
#
# Payload: { "version": "...", "sha": "...", "timestamp": "..." }
#
# Examples:
#   website deploy --version "v1.3.0" --sha "abc1234"
export def "website deploy" [
    --version: string = "unknown"  # Semantic version or git tag
    --sha:     string = ""         # Git commit SHA (optional)
    --url:     string = ""
    --creds:   string = ""
] {
    let subject = build-admin-subject "ops.deploy"
    let ts = date now | format date "%Y-%m-%dT%H:%M:%SZ"
    let payload = { version: $version, sha: $sha, timestamp: $ts } | to json --raw

    nats-pub $subject $payload --url $url --creds $creds
    print $"Deploy signal published — version: ($version)"
}

# Trigger a hot config-reload on the running server (rbac.ncl, external-services, etc.).
#
# The server's config-reload handler receives this signal and re-reads all
# hot-reloadable config files.  No restart required.
#
# Examples:
#   website reload
#   website reload --reason "updated rbac.ncl"
export def "website reload" [
    --reason: string = ""  # Optional human-readable reason (logged server-side)
    --url:    string = ""
    --creds:  string = ""
] {
    let subject = build-admin-subject "ops.config-reload"
    let payload = { reason: $reason } | to json --raw

    nats-pub $subject $payload --url $url --creds $creds
    print "Config-reload signal published."
}
