#!/usr/bin/env node
/**
 * E2E WebSocket Listener — waits for a specific realtime event.
 *
 * Usage:
 *   node e2e-ws-listener.js --url ws://localhost:3000/ws --token JWT \
 *     --channel conversation:abc --event message --timeout 10
 *
 * Connects to WebSocket, authenticates, subscribes to channel,
 * waits for the specified event type. Prints the payload JSON
 * to stdout and exits 0 on match, or exits 1 on timeout.
 */
const WebSocket = require('ws');

const args = {};
for (let i = 2; i < process.argv.length; i += 2) {
  args[process.argv[i].replace('--', '')] = process.argv[i + 1];
}

const url     = args.url || 'ws://localhost:3000/ws';
const token   = args.token || '';
const channel = args.channel || '';
const event   = args.event || 'message';
const timeout = parseInt(args.timeout || '10', 10) * 1000;

if (!token || !channel) {
  console.error('Usage: --url WS_URL --token JWT --channel CHANNEL --event EVENT [--timeout SECS]');
  process.exit(1);
}

const ws = new WebSocket(url);
let timer = null;

ws.on('open', () => {
  // Authenticate
  ws.send(JSON.stringify({ type: 'auth', token: token }));
  // Subscribe to channel
  ws.send(JSON.stringify({ type: 'room.subscribe', room: channel }));
});

ws.on('message', (data) => {
  try {
    const msg = JSON.parse(data.toString());
    // Match event on the subscribed channel
    if (msg.type === 'event' && msg.channel === channel && msg.event === event) {
      console.log(JSON.stringify(msg.data || msg));
      clearTimeout(timer);
      ws.close();
      process.exit(0);
    }
  } catch (e) {
    // Ignore non-JSON messages
  }
});

ws.on('error', (err) => {
  console.error('WS error:', err.message);
  process.exit(1);
});

timer = setTimeout(() => {
  console.error('Timeout waiting for event: ' + event + ' on channel: ' + channel);
  ws.close();
  process.exit(1);
}, timeout);
