#!/usr/bin/env bash
# Read every page of a list: follow next_cursor, with the same filters, until has_more is false.
# Requires bash, curl and jq. Read-only: works with a test or a live key.
#
#   export RELATIONSAI_API_KEY="rai_test_..."
#   bash pagination.sh
set -euo pipefail

BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
BASE="${BASE%/}"
if [[ "${RELATIONSAI_API_KEY:-}" != rai_* ]]; then
  echo "Set RELATIONSAI_API_KEY to an API key (rai_test_... or rai_live_...)." >&2
  exit 1
fi

BODY_FILE="$(mktemp)" OUTCOMES="$(mktemp)"
trap 'rm -f "$BODY_FILE" "$OUTCOMES"' EXIT

# Every ended call of the last 24 hours, counted by outcome. (GNU date first, then BSD/macOS date.)
since="$(date -u -d '24 hours ago' +%Y-%m-%dT%H:%M:%S.000Z 2>/dev/null || date -u -v-24H +%Y-%m-%dT%H:%M:%S.000Z)"

cursor=""
while :; do
  # --data-urlencode encodes every value, including the "+" of an E.164 number (as %2B).
  # The filters stay identical on every page: a cursor is bound to them.
  args=(-sS -G "$BASE/calls" -H "Authorization: Bearer $RELATIONSAI_API_KEY" --max-time 30
    --data-urlencode "status=ended" --data-urlencode "created_after=$since" --data-urlencode "limit=100"
    -o "$BODY_FILE" -w '%{http_code}')
  if [[ -n "$cursor" ]]; then args+=(--data-urlencode "cursor=$cursor"); fi
  status="$(curl "${args[@]}")"
  if (( status >= 400 )); then
    jq -r --arg s "$status" '"\($s) \(.error.code) (request \(.error.request_id)): \(.error.message)"' "$BODY_FILE" >&2
    exit 1
  fi
  jq -r '.data[] | .outcome // "unknown"' "$BODY_FILE" >>"$OUTCOMES"
  cursor="$(jq -r 'if .has_more then .next_cursor else empty end' "$BODY_FILE")"
  if [[ -z "$cursor" ]]; then break; fi
done

echo "Ended calls since $since: $(wc -l <"$OUTCOMES" | tr -d ' ')"
sort "$OUTCOMES" | uniq -c | awk '{ print "  " $2 ": " $1 }'
