#!/usr/bin/env bash
# Cancel the test customer's most-recent in-flight blast (pairing request).
# Used by ts-mitra-3-07-popup_cancelled_by_customer.yaml to drive the
# "Permintaan dibatalkan oleh klien" stale-card UX on the mitra side
# without waiting on any timer.
#
# The payment_session_id is sourced from /tmp/halobestie_last_blast_payment_session_id
# which customer_blast_now.sh writes on every blast. Callers must run
# customer_blast_now.sh first.
#
# Hits POST /api/client/chat-requests/cancel with TEST_CUSTOMER_JWT. The
# pairing service emits `chat_request_closed reason=cancelled_by_customer`
# to every mitra that received the blast (pairing.service.js:585-592).

set -euo pipefail

: "${BACKEND_URL:?BACKEND_URL must be set in .maestro/config.yaml}"
: "${TEST_CUSTOMER_JWT:?TEST_CUSTOMER_JWT must be set in .maestro/config.yaml}"

PAYMENT_SESSION_ID_FILE="/tmp/halobestie_last_blast_payment_session_id"
if [[ ! -s "$PAYMENT_SESSION_ID_FILE" ]]; then
  echo "ERROR: $PAYMENT_SESSION_ID_FILE missing or empty — run customer_blast_now.sh first"
  exit 2
fi
PAYMENT_SESSION_ID=$(cat "$PAYMENT_SESSION_ID_FILE")

echo "Cancelling pairing for payment_session_id=$PAYMENT_SESSION_ID..."
curl -fsSL -X POST "$BACKEND_URL/api/client/chat-requests/cancel" \
  -H "Authorization: Bearer $TEST_CUSTOMER_JWT" \
  -H "Content-Type: application/json" \
  -d "{\"payment_session_id\":\"$PAYMENT_SESSION_ID\"}" > /dev/null

echo "OK — cancel fired. Mitra should see chat_request_closed within ~1s."
