#!/usr/bin/env bash
# Create or update the contact with this phone number. Needs: curl, jq.
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
PHONE="${PHONE:-+12025550100}"

body=$(jq -n --arg phone "$PHONE" '{phone_number: $phone, name: "Asha Rao", language: "en"}')
if [ "${CONSENT_GRANTED:-}" = "true" ]; then
  # CONSENT_GRANTED=true records consent: set it only when the person really agreed to be called.
  body=$(jq '. + {consent_granted: true}' <<<"$body")
fi

out=$(mktemp)
status=$(curl -sS -o "$out" -w '%{http_code}' -X POST "$BASE/contacts/upsert" \
  -H "Authorization: Bearer $RELATIONSAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$body")
case "$status" in
  201) echo "Created $(jq -r '.id' "$out")" ;;
  200) echo "Updated $(jq -r '.id' "$out")" ;;
  *) cat "$out" >&2; exit 1 ;;
esac
jq -r '"phone=\(.phone_number) consent=\(.consent_granted) do_not_call=\(.do_not_call)"' "$out"
