// 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.
//
// Reads PAYMENT_SESSION_ID and TEST_CUSTOMER_JWT from `output` — both set by
// customer_blast_now.js, so callers must run customer_blast_now.js first
// in the same flow.
//
// Hits POST /api/client/chat-requests/cancel. The pairing service emits
// `chat_request_closed reason=cancelled_by_customer` to every mitra that
// received the blast (pairing.service.js:585-592).

const backend = BACKEND_URL || 'http://localhost:3000'

if (!output.PAYMENT_SESSION_ID) {
  throw new Error('PAYMENT_SESSION_ID missing — run customer_blast_now.js first')
}
const token = output.TEST_CUSTOMER_JWT || TEST_CUSTOMER_JWT
if (!token || token.startsWith('REPLACE')) {
  throw new Error('TEST_CUSTOMER_JWT missing — customer_blast_now.js should have set output.TEST_CUSTOMER_JWT')
}

const resp = http.post(`${backend}/api/client/chat/chat-requests/cancel`, {
  headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
  body: JSON.stringify({ payment_session_id: output.PAYMENT_SESSION_ID }),
})
if (resp.status !== 200 && resp.status !== 201 && resp.status !== 204) {
  throw new Error(`cancel-pairing failed (${resp.status}): ${resp.body}`)
}
console.log('cancel fired for payment_session_id:', output.PAYMENT_SESSION_ID)
