// Assert backend's in-memory WS connection state for a session matches
// expectations. Throws (fails the maestro flow) on mismatch.
//
// Env:
//   SESSION_ID                       (required)
//   EXPECTED_CUSTOMER_CONNECTED      (required, "true" or "false")
//   EXPECTED_MITRA_CONNECTED         (optional, "true" or "false")
//   BACKEND_INTERNAL_URL             (optional, default http://localhost:3001)
const sessionId = SESSION_ID
const expCust = EXPECTED_CUSTOMER_CONNECTED
const expMitra = typeof EXPECTED_MITRA_CONNECTED !== 'undefined' ? EXPECTED_MITRA_CONNECTED : null
const url = BACKEND_INTERNAL_URL || 'http://localhost:3001'
if (!sessionId) throw new Error('SESSION_ID env not set')
if (expCust !== 'true' && expCust !== 'false') {
  throw new Error('EXPECTED_CUSTOMER_CONNECTED must be "true" or "false"')
}

const resp = http.get(`${url}/internal/_test/ws-connection-state?session_id=${sessionId}`)
if (resp.status !== 200) {
  throw new Error(`ws-connection-state failed (${resp.status}): ${resp.body}`)
}
const data = json(resp.body)

const gotCust = String(data.customer_connected)
if (gotCust !== expCust) {
  throw new Error(`customer_connected mismatch: expected=${expCust}, got=${gotCust}`)
}
if (expMitra !== null) {
  const gotMitra = String(data.mitra_connected)
  if (gotMitra !== expMitra) {
    throw new Error(`mitra_connected mismatch: expected=${expMitra}, got=${gotMitra}`)
  }
}
output.CUSTOMER_CONNECTED = gotCust
output.MITRA_CONNECTED = String(data.mitra_connected)
