// Local tutorial client. Reject remote destinations; never use production credentials.
import assert from 'node:assert/strict';

const base = new URL(process.argv[2] ?? 'http://127.0.0.1:4319');
if (base.protocol !== 'http:' || base.hostname !== '127.0.0.1' || base.username || base.password) {
  throw new Error('This teaching client accepts only a loopback HTTP destination.');
}
const headers = {
  authorization: 'Bearer local-demo-only',
  'content-type': 'application/json',
  'idempotency-key': 'tutorial-workspace-001',
};
const body = JSON.stringify({ name: 'workspace.created', properties: { workspace_id: 'ws_example_001' } });
const options = { signal: AbortSignal.timeout(3000), redirect: 'error' };
const response = await fetch(new URL('/v1/events', base), { ...options, method: 'POST', headers, body });
assert.equal(response.status, 202, 'Expected acceptance; inspect status before using the response.');
const receipt = await response.json();
assert.equal(typeof receipt.event_id, 'string');
assert.match(receipt.event_id, /^evt_[1-9][0-9]*$/);
assert.equal(receipt.status, 'accepted');
const stored = await fetch(new URL(`/v1/events/${receipt.event_id}`, base), {
  headers: { authorization: headers.authorization }, signal: AbortSignal.timeout(3000), redirect: 'error',
});
assert.equal(stored.status, 200);
assert.deepEqual(await stored.json(), receipt);
process.stdout.write(JSON.stringify({ checked: 'accepted receipt, not downstream delivery', ...receipt }) + '\n');
