import { test } from 'node:test';
import assert from 'node:assert/strict';
import { once } from 'node:events';
import WebSocket from 'ws';
import { checkpoint } from './checkpoint.js';

test('the exact introductory ESM entry points start real listeners', { timeout: 25000 }, async () => {
    for (const [name, content] of [['hello', 'Hello world!'], ['counter', 'rw-click="increment"'], ['http-ws', 'Hello from HTTP!']]) {
        const app = await checkpoint(name);
        try {
            assert.ok((await (await fetch(app.origin)).text()).includes(content));
            if (name === 'http-ws') {
                const socket = new WebSocket('ws://localhost:8181/chat');
                try {
                    await once(socket, 'open', { signal: AbortSignal.timeout(5000) });
                    const message = once(socket, 'message', { signal: AbortSignal.timeout(5000) });
                    socket.send(JSON.stringify({ type: 'hello' }));
                    assert.equal(JSON.parse(String((await message)[0])).message, 'Hello from WebSockets!');
                } finally { socket.terminate(); }
            }
        } finally { await app.close(); }
    }
});
