#!/usr/bin/env bash
# Send a webhook_endpoint.test event to an endpoint, then show its recent deliveries. Needs: curl, jq.
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
: "${WEBHOOK_ENDPOINT_ID:?Set WEBHOOK_ENDPOINT_ID to an endpoint id (we_...)}"
AUTH="Authorization: Bearer $RELATIONSAI_API_KEY"

delivery=$(curl -sS --fail-with-body -X POST "$BASE/webhook-endpoints/$WEBHOOK_ENDPOINT_ID/test" \
  -H "$AUTH") || { echo "$delivery" >&2; exit 1; }
jq -r '"Queued \(.id) for event \(.event_id) status=\(.status)"' <<<"$delivery"

sleep "${WAIT_SECONDS:-5}"
deliveries=$(curl -sS --fail-with-body "$BASE/webhook-endpoints/$WEBHOOK_ENDPOINT_ID/deliveries?limit=5" -H "$AUTH") ||
  { echo "$deliveries" >&2; exit 1; }
jq -r '.data[] | "\(.id) \(.event_type) \(.status) attempts=\(.attempts) http=\(.response_status) error=\(.error)"' <<<"$deliveries"
