#!/usr/bin/env bash
# Turn one CRM event into a contact update and a call, safely repeatable. Needs: curl, jq.
# Every request runs, so before calling, the script looks for a call already placed for this CRM event
# (by the crm_event_id in metadata): the same event never places a second call.
set -euo pipefail
BASE="${RELATIONSAI_API_BASE:-https://voice-api.relationsai.com/v1}"
AGENT_ID="${AGENT_ID:-agent_1ZltiWzxrXmMprGD6q63}" # the test-mode Sample agent unless you set your own
EVENT_ID="${CRM_EVENT_ID:-E-9001}" RECORD_ID="${CRM_RECORD_ID:-L-1042}" PHONE="${PHONE:-+12025550100}"
AUTH="Authorization: Bearer $RELATIONSAI_API_KEY"

post() { # path, JSON body
  local out
  out=$(curl -sS --fail-with-body -X POST "$BASE$1" -H "$AUTH" \
    -H "Content-Type: application/json" -d "$2") || { echo "$1: $out" >&2; return 1; }
  echo "$out"
}

contact=$(post /contacts/upsert "$(jq -n --arg p "$PHONE" '{phone_number: $p, name: "Asha"}')")

# Already called for this CRM event? Look at the calls to this number in the last day.
since=$(date -u -v-1d +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -d '1 day ago' +%Y-%m-%dT%H:%M:%SZ)
recent=$(curl -sS --fail-with-body -G "$BASE/calls" -H "$AUTH" --data-urlencode "to=$PHONE" \
  --data-urlencode "created_after=$since" --data-urlencode "limit=100") || { echo "$recent" >&2; exit 1; }
existing=$(jq -r --arg e "$EVENT_ID" '[.data[] | select(.metadata.crm_event_id == $e)][0].id // empty' <<<"$recent")
if [ -n "$existing" ]; then
  echo "$RECORD_ID: already called for $EVENT_ID ($existing), not calling again"
  exit 0
fi

call=$(post /calls "$(jq -n --arg a "$AGENT_ID" --arg p "$PHONE" --arg r "$RECORD_ID" --arg e "$EVENT_ID" \
  '{agent_id: $a, to: $p, variables: {first_name: "Asha"}, metadata: {crm_record_id: $r, crm_event_id: $e}}')")
echo "$RECORD_ID: contact $(jq -r '.id' <<<"$contact"), call $(jq -r '.id' <<<"$call") $(jq -r '.status' <<<"$call")"
