# Shared helpers for examples/curl/*.sh
# shellcheck shell=bash

ORIGIN="${ATHENA_AUTH_ORIGIN:-http://localhost:3000}"
AUTH_BASE="${ATHENA_AUTH_BASE:-${ORIGIN}/api/auth}"
COOKIE_JAR="${ATHENA_AUTH_COOKIE_JAR:-${TMPDIR:-/tmp}/athena-auth-examples.cookies}"

pretty() {
  if command -v jq >/dev/null 2>&1; then
    jq .
  else
    cat
  fi
}

require_env() {
  local n="$1"
  if [[ -z "${!n:-}" ]]; then
    echo "Missing env: $n" >&2
    exit 1
  fi
}

curl_get() {
  local path="$1"
  shift || true
  curl -sS "$@" -X GET "${AUTH_BASE}${path}"
}

curl_get_bearer() {
  local path="$1"
  local token="$2"
  shift 2 || true
  curl -sS "$@" -X GET "${AUTH_BASE}${path}" \
    -H "Authorization: Bearer ${token}"
}

curl_post_json() {
  local path="$1"
  local json="$2"
  shift 2 || true
  curl -sS "$@" -X POST "${AUTH_BASE}${path}" \
    -H "Content-Type: application/json" \
    -d "${json}"
}

curl_post_bearer_json() {
  local path="$1"
  local token="$2"
  local json="$3"
  shift 3 || true
  curl -sS "$@" -X POST "${AUTH_BASE}${path}" \
    -H "Authorization: Bearer ${token}" \
    -H "Content-Type: application/json" \
    -d "${json}"
}

curl_post_json_cookies() {
  local path="$1"
  local json="$2"
  curl -sS -c "${COOKIE_JAR}" -b "${COOKIE_JAR}" \
    -X POST "${AUTH_BASE}${path}" \
    -H "Content-Type: application/json" \
    -d "${json}"
}

curl_get_cookies() {
  local path="$1"
  curl -sS -b "${COOKIE_JAR}" -X GET "${AUTH_BASE}${path}"
}
