import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createExampleServer } from './api-example.mjs';

const server = createExampleServer();
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const base = `http://127.0.0.1:${server.address().port}`;
const headers = { authorization: 'Bearer local-demo-only', 'content-type': 'application/json', 'idempotency-key': 'demo-001' };
const body = JSON.stringify({ name: 'workspace.created', properties: { workspace_id: 'ws_example_001' } });
const post = (text, h = headers) => fetch(base + '/v1/events', { method: 'POST', headers: h, body: text });
const results = [];
try {
  const first = await post(body); assert.equal(first.status, 202);
  const receipt = await first.json(); assert.deepEqual(receipt, { event_id: 'evt_1', status: 'accepted' }); results.push('accepted request');
  const replay = await post(body); assert.equal(replay.status, 202); assert.deepEqual(await replay.json(), receipt); results.push('identical replay retains receipt');
  const changed = await post(JSON.stringify({ name: 'different', properties: {} })); assert.equal(changed.status, 409); results.push('changed body conflicts');
  const missing = await post(body, { ...headers, authorization: 'Bearer wrong' }); assert.equal(missing.status, 401); assert.ok(missing.headers.get('www-authenticate')); results.push('invalid credential rejected');
  assert.equal((await post('{bad')).status, 400); results.push('invalid JSON rejected');
  assert.equal((await post(JSON.stringify({ name: '', properties: {} }))).status, 400); results.push('invalid contract rejected');
  const noKey = { ...headers }; delete noKey['idempotency-key']; assert.equal((await post(body, noKey)).status, 400); results.push('missing key rejected');
  assert.equal((await post(body, { ...headers, 'content-type': 'text/plain' })).status, 415); results.push('wrong media type rejected');
  const read = await fetch(base + '/v1/events/evt_1', { headers }); assert.equal(read.status, 200); assert.deepEqual(await read.json(), receipt); results.push('receipt readable; no delivery claim');
  assert.equal((await fetch(base + '/v1/events/unknown', { headers })).status, 404); results.push('missing receipt rejected');
  const parallel = await Promise.all([post(body, { ...headers, 'idempotency-key': 'parallel' }), post(body, { ...headers, 'idempotency-key': 'parallel' })]);
  for (const response of parallel) assert.equal(response.status, 202);
  const [a,b] = await Promise.all(parallel.map(r => r.json()));
  for (const receipt of [a,b]) {
    assert.equal(typeof receipt.event_id, 'string');
    assert.match(receipt.event_id, /^evt_[1-9][0-9]*$/);
    assert.equal(receipt.status, 'accepted');
  }
  assert.equal(a.event_id,b.event_id); results.push('same-key concurrent requests return valid 202 receipts with identical IDs');
  process.stdout.write(JSON.stringify({ node: process.version, passed: results.length, results }, null, 2) + '\n');
} finally {
  server.closeAllConnections();
  await new Promise(resolve => server.close(resolve));
}
