#!/usr/bin/env bash
# Change a campaign's concurrency with If-Match. Needs: curl, jq.
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
: "${CAMPAIGN_ID:?Set CAMPAIGN_ID to a campaign id (cmp_...)}"
AUTH="Authorization: Bearer $RELATIONSAI_API_KEY"

headers=$(mktemp)
campaign=$(curl -sS --fail-with-body -D "$headers" "$BASE/campaigns/$CAMPAIGN_ID" -H "$AUTH") ||
  { echo "$campaign" >&2; exit 1; }
etag=$(tr -d '\r' <"$headers" | awk -F': ' 'tolower($1)=="etag" {print $2}')

# 409 campaign_state_conflict: it is running; pause or stop it first.
# 412 version_conflict: it changed since this read; read again and decide again.
updated=$(curl -sS --fail-with-body -X PATCH "$BASE/campaigns/$CAMPAIGN_ID" \
  -H "$AUTH" -H "If-Match: $etag" -H "Content-Type: application/json" \
  -d '{"concurrency_limit": 3}') || { echo "$updated" >&2; exit 1; }
jq -r '"\(.id) concurrency_limit=\(.concurrency_limit) status=\(.status)"' <<<"$updated"
