# Helper for loading NATS credentials and URL in deploy scripts.
load_nats_env() {
  : "${NATS_HOST:?missing NATS_HOST}"
  : "${NATS_PORT:?missing NATS_PORT}"

  nats_secret_path="${NATS_SECRET_PATH:-sendico/nats}"
  export NATS_USER="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${nats_secret_path}" user)"
  export NATS_PASSWORD="$(sh ci/scripts/common/runtime_kv_get.sh kv_get kv "${nats_secret_path}" password)"

  nats_url_var="${NATS_URL_VAR:-NATS_URL}"
  nats_url_scheme="${NATS_URL_SCHEME:-nats}"
  case "${nats_url_var}" in
    ''|[!A-Za-z_]*|*[!A-Za-z0-9_]*)
      echo "[nats-env] invalid NATS_URL_VAR: ${nats_url_var}" >&2
      exit 1
      ;;
  esac

  export "${nats_url_var}=${nats_url_scheme}://${NATS_HOST}:${NATS_PORT}"
}
