// Local teaching fixture only. No production credentials, persistence, or OAuth server.
import http from 'node:http';
import { pathToFileURL } from 'node:url';

export function createExampleServer() {
  const events = new Map();
  const keys = new Map();
  let sequence = 0;
  return http.createServer(async (req, res) => {
    const send = (status, data, extra = {}) => {
      res.writeHead(status, { 'content-type': 'application/json', ...extra });
      res.end(JSON.stringify(data));
    };
    if (req.headers.authorization !== 'Bearer local-demo-only') {
      return send(401, { error: 'invalid_token' }, { 'www-authenticate': 'Bearer realm="local-example"' });
    }
    if (req.method === 'GET' && req.url?.startsWith('/v1/events/')) {
      const event = events.get(req.url.split('/').at(-1));
      return event ? send(200, event) : send(404, { error: 'not_found' });
    }
    if (req.method !== 'POST' || req.url !== '/v1/events') return send(404, { error: 'not_found' });
    if (req.headers['content-type']?.split(';')[0] !== 'application/json') {
      return send(415, { error: 'json_required' });
    }
    const key = req.headers['idempotency-key'];
    if (typeof key !== 'string' || !key.trim() || key.length > 128) {
      return send(400, { error: 'idempotency_key_required' });
    }
    let raw = '';
    try {
      for await (const chunk of req) {
        raw += chunk.toString('utf8');
        if (Buffer.byteLength(raw) > 16384) return send(413, { error: 'body_too_large' });
      }
    } catch {
      return send(400, { error: 'incomplete_body' });
    }
    let body;
    try { body = JSON.parse(raw); } catch { return send(400, { error: 'invalid_json' }); }
    if (!body || typeof body !== 'object' || Array.isArray(body) ||
      typeof body.name !== 'string' || !body.name.trim() ||
      !body.properties || typeof body.properties !== 'object' || Array.isArray(body.properties)) {
      return send(400, { error: 'invalid_event' });
    }
    // Equality is exact request-body text, not semantic JSON equivalence.
    const previous = keys.get(key);
    if (previous) {
      return previous.raw === raw
        ? send(202, previous.receipt)
        : send(409, { error: 'key_reused_with_different_body' });
    }
    const receipt = { event_id: `evt_${++sequence}`, status: 'accepted' };
    keys.set(key, { raw, receipt });
    events.set(receipt.event_id, receipt);
    return send(202, receipt);
  });
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const server = createExampleServer();
  server.listen(Number(process.argv[2] ?? 4319), '127.0.0.1', () => {
    process.stdout.write(`Local teaching API: http://127.0.0.1:${server.address().port}\n`);
  });
}
