#!/usr/bin/env bash
# Rotate an endpoint's signing secret. The old one keeps signing for GRACE_HOURS (0 retires every older secret now). 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_...)}"
GRACE_HOURS="${GRACE_HOURS:-24}"

endpoint=$(curl -sS --fail-with-body -X POST "$BASE/webhook-endpoints/$WEBHOOK_ENDPOINT_ID/rotate-secret" \
  -H "Authorization: Bearer $RELATIONSAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"grace_period_hours\": $GRACE_HOURS}") || { echo "$endpoint" >&2; exit 1; }

echo "New secret for $(jq -r '.id' <<<"$endpoint") (shown once): $(jq -r '.secret' <<<"$endpoint")"
echo "Deploy it before the grace period ($GRACE_HOURS h) ends; until then deliveries carry both signatures."
