#!/usr/bin/env bash
# Register a webhook endpoint for the key's mode. Prints the signing secret once. Needs: curl, jq.
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
: "${WEBHOOK_URL:?Set WEBHOOK_URL to your public HTTPS endpoint}"

endpoint=$(curl -sS --fail-with-body -X POST "$BASE/webhook-endpoints" \
  -H "Authorization: Bearer $RELATIONSAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg url "$WEBHOOK_URL" '{
        url: $url,
        description: "CRM sync",
        events: ["call.ended", "call.settled", "campaign.completed"]
      }')") || { echo "$endpoint" >&2; exit 1; }

jq -r '"Created \(.id) livemode=\(.livemode) events=\(.events | join(","))"' <<<"$endpoint"
# Shown only in this response: put it in your secret store now.
jq -r '"Signing secret: \(.secret)"' <<<"$endpoint"
