// P9 scaling smoke: cross-instance realtime fan-out via the socket.io Redis adapter.
// Alice connects to instance A, Bob to instance B (two separate processes sharing one
// Redis + DB). Alice sends on A; Bob must receive it live on B — which only works if the
// Redis adapter fans room emits across replicas. Set A_URL / B_URL (default 3201/3202).
import 'dotenv/config';
import { io } from 'socket.io-client';
import jwt from 'jsonwebtoken';

const A_URL = process.env.A_URL ?? 'http://localhost:3201';
const B_URL = process.env.B_URL ?? 'http://localhost:3202';
const APP_ID = 'portal-demo';
const SECRET = JSON.parse(process.env.APP_SECRETS ?? '{"portal-demo":"dev-secret"}')[APP_ID];

const sign = (userId) =>
  jwt.sign({ sub: userId, name: userId, appId: APP_ID, orgId: `org_${APP_ID}` }, SECRET, { algorithm: 'HS256', expiresIn: '1h' });
const connect = (url, userId) =>
  io(`${url}/message`, { auth: { token: sign(userId) }, transports: ['websocket'], forceNew: true });
const once = (socket, event, ms = 8000) =>
  new Promise((res, rej) => {
    const t = setTimeout(() => rej(new Error(`timeout waiting for "${event}"`)), ms);
    socket.once(event, (v) => { clearTimeout(t); res(v); });
  });
const assert = (c, m) => { if (!c) { console.error('✗', m); process.exit(1); } console.log('✓', m); };

const alice = connect(A_URL, 'alice-cluster');
const bob = connect(B_URL, 'bob-cluster');

try {
  await Promise.all([once(alice, 'connect'), once(bob, 'connect')]);
  assert(true, `Alice connected to A (${A_URL}), Bob to B (${B_URL})`);

  // Alice opens a thread on instance A; membership is governed so Alice ADDS Bob, who
  // then opens the SAME thread on instance B.
  const opened = await alice.emitWithAck('open_thread', {});
  const threadId = opened.threadId;
  assert(!!threadId, `Alice opened thread ${threadId} on instance A`);
  await alice.emitWithAck('add_participant', { threadId, userId: 'bob-cluster' });
  await bob.emitWithAck('open_thread', { threadId });
  assert(true, 'Bob joined the same thread on instance B');

  // Alice sends on A → Bob must receive it on B (cross-instance fan-out via Redis).
  const bobReceives = once(bob, 'message');
  await alice.emitWithAck('send_message', { threadId, content: 'hello across instances' });
  const received = await bobReceives;
  assert(received.content === 'hello across instances', `Bob received "${received.content}" on B — emitted from A ✓`);

  console.log('\nP9 cross-instance realtime smoke: PASS');
} catch (err) {
  console.error('✗', err.message);
  process.exit(1);
} finally {
  alice.close();
  bob.close();
}
process.exit(0);
