// Send a chat message AS the given side and assert the delivery transport
// matches EXPECTED_DELIVERED_VIA. Throws on mismatch.
//
// Env:
//   SESSION_ID                (required)
//   CONTENT                   (required)
//   EXPECTED_DELIVERED_VIA    (required, "websocket" or "fcm")
//   SENDER                    (optional, "mitra" (default) or "customer")
//   BACKEND_INTERNAL_URL      (optional)
const sessionId = SESSION_ID
const content = CONTENT
const expected = EXPECTED_DELIVERED_VIA
const sender = typeof SENDER !== 'undefined' && SENDER ? SENDER : 'mitra'
const url = BACKEND_INTERNAL_URL || 'http://localhost:3001'
if (!sessionId) throw new Error('SESSION_ID env not set')
if (!content) throw new Error('CONTENT env not set')
if (expected !== 'websocket' && expected !== 'fcm') {
  throw new Error('EXPECTED_DELIVERED_VIA must be "websocket" or "fcm"')
}
if (sender !== 'mitra' && sender !== 'customer') {
  throw new Error('SENDER must be "mitra" or "customer"')
}

const endpoint =
  sender === 'mitra'
    ? '/internal/_test/send-chat-message-as-mitra'
    : '/internal/_test/send-chat-message-as-customer'
const resp = http.post(`${url}${endpoint}`, {
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ session_id: sessionId, content }),
})
if (resp.status !== 200) {
  throw new Error(`send-chat-message-as-mitra failed (${resp.status}): ${resp.body}`)
}
const data = json(resp.body)
if (data.delivered_via !== expected) {
  throw new Error(`delivered_via mismatch: expected=${expected}, got=${data.delivered_via}`)
}
output.MESSAGE_ID = data.message_id
output.DELIVERED_VIA = data.delivered_via
