import { describe, expect, it } from 'bun:test';
import {
  MemoryShadeBridge,
  WebRtcSignalingChannel,
} from '../src/signaling.js';

describe('WebRtcSignalingChannel', () => {
  it('routes typed signaling messages through the bridge', async () => {
    const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
    const aliceSig = new WebRtcSignalingChannel(a);
    const bobSig = new WebRtcSignalingChannel(b);

    const received: Array<{ from: string; kind: string }> = [];
    bobSig.onSignal((from, msg) => {
      received.push({ from, kind: msg.kind });
    });

    await aliceSig.sendOffer('bob', 'sess-1', 'v=0\nfake-sdp');
    await aliceSig.sendIce('bob', 'sess-1', {
      candidate: 'candidate:1 1 udp 0 1.2.3.4 1234 typ host',
      sdpMid: '0',
      sdpMLineIndex: 0,
    });
    await aliceSig.sendBye('bob', 'sess-1', 'no longer needed');

    expect(received).toEqual([
      { from: 'alice', kind: 'shade.webrtc-offer/v1' },
      { from: 'alice', kind: 'shade.webrtc-ice/v1' },
      { from: 'alice', kind: 'shade.webrtc-bye/v1' },
    ]);

    aliceSig.destroy();
    bobSig.destroy();
  });

  it('passes non-signaling messages through to the passthrough hook', async () => {
    const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
    const passthrough: string[] = [];
    const bobSig = new WebRtcSignalingChannel(b, {
      passthrough: (_from, plaintext) => passthrough.push(plaintext),
    });
    const seen: string[] = [];
    bobSig.onSignal((_from, msg) => seen.push(msg.kind));

    await a.send('bob', 'hello world (not signaling)');
    await a.send('bob', JSON.stringify({ kind: 'shade.fs.cancel/v1' }));

    expect(passthrough).toContain('hello world (not signaling)');
    expect(seen).toEqual([]);
    bobSig.destroy();
  });

  it('preserves causal order — offer awaited before ICE handler runs', async () => {
    const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
    const aliceSig = new WebRtcSignalingChannel(a);
    const bobSig = new WebRtcSignalingChannel(b);
    const order: string[] = [];

    bobSig.onSignal(async (_from, msg) => {
      if (msg.kind === 'shade.webrtc-offer/v1') {
        // Slow handler — must complete before ICE arrives.
        await new Promise<void>((resolve) => setTimeout(resolve, 25));
        order.push('offer-done');
      } else if (msg.kind === 'shade.webrtc-ice/v1') {
        order.push('ice');
      }
    });

    await aliceSig.sendOffer('bob', 's', 'sdp');
    await aliceSig.sendIce('bob', 's', null);

    expect(order).toEqual(['offer-done', 'ice']);
    aliceSig.destroy();
    bobSig.destroy();
  });
});
