// rootzero educational fixture. Node.js 24, no dependencies, no target argument.
// Creates only ephemeral loopback servers and fictional in-memory invoices.
import { createServer } from 'node:http';
import { createHash } from 'node:crypto';

const fixture = {
  "application": "Invoice Demo",
  "baseUrl": "https://api.example.invalid/v1",
  "accounts": [
    {
      "id": "viewerA",
      "role": "viewer",
      "tenant": "tenantA"
    },
    {
      "id": "editorA",
      "role": "editor",
      "tenant": "tenantA"
    },
    {
      "id": "adminA",
      "role": "admin",
      "tenant": "tenantA"
    },
    {
      "id": "viewerB",
      "role": "viewer",
      "tenant": "tenantB"
    }
  ],
  "resources": [
    {
      "id": "invoiceA",
      "tenant": "tenantA"
    },
    {
      "id": "invoiceB",
      "tenant": "tenantB"
    }
  ],
  "cases": [
    {
      "id": "C01",
      "account": "viewerA",
      "resource": "invoiceA",
      "operation": "readInvoice",
      "expected": "allow"
    },
    {
      "id": "C02",
      "account": "viewerA",
      "resource": "invoiceB",
      "operation": "readInvoice",
      "expected": "deny"
    },
    {
      "id": "C03",
      "account": "viewerB",
      "resource": "invoiceB",
      "operation": "readInvoice",
      "expected": "allow"
    },
    {
      "id": "C04",
      "account": "viewerB",
      "resource": "invoiceA",
      "operation": "readInvoice",
      "expected": "deny"
    },
    {
      "id": "C05",
      "account": "editorA",
      "resource": "invoiceA",
      "operation": "updateInvoice",
      "expected": "allow"
    },
    {
      "id": "C06",
      "account": "viewerA",
      "resource": "invoiceA",
      "operation": "updateInvoice",
      "expected": "deny"
    },
    {
      "id": "C07",
      "account": "adminA",
      "resource": "invoiceA",
      "operation": "updateInvoice",
      "expected": "allow"
    },
    {
      "id": "C08",
      "account": "adminA",
      "resource": "invoiceB",
      "operation": "updateInvoice",
      "expected": "deny"
    }
  ]
};
if (process.argv.slice(2).length) throw new Error('This demo accepts no arguments or external target.');
const observations = [];
const controls = [];

for (const mode of ['missing_authorisation', 'tenant_and_role_checked']) {
  const invoices = new Map(fixture.resources.map(r => [r.id, { ...r, note: 'fictional initial value' }]));
  const server = createServer((req, res) => {
    const send = (status, body) => {
      res.writeHead(status, { 'Content-Type': 'application/json', 'Connection': 'close' });
      res.end(JSON.stringify(body));
    };
    // Mock authentication: these known demo tokens are NOT production auth.
    const account = fixture.accounts.find(a => req.headers.authorization === `Bearer demo-${a.id}`);
    if (!account) return send(401, { error: 'demo_authentication_required' });
    const match = /^\/v1\/invoices\/(invoiceA|invoiceB)$/.exec(req.url);
    if (!match || !['GET', 'PATCH'].includes(req.method)) return send(404, { error: 'not_found' });
    const invoice = invoices.get(match[1]);
    // Tenant comes from the authenticated server-side identity, never a tenant header.
    if (mode === 'tenant_and_role_checked' &&
      (account.tenant !== invoice.tenant || (req.method === 'PATCH' && !['editor', 'admin'].includes(account.role)))) {
      return send(403, { error: 'forbidden' });
    }
    // Simulated write: one bounded, fictional value, no external side effects.
    if (req.method === 'PATCH') invoice.note = `fictional update by ${account.id}`;
    send(200, invoice);
  });
  server.requestTimeout = 3000;
  server.headersTimeout = 3000;
  await new Promise((resolve, reject) => {
    server.once('error', reject);
    server.listen(0, '127.0.0.1', resolve);
  });
  const base = `http://127.0.0.1:${server.address().port}`;
  const request = async (resource, method, token, headers = {}) => {
    const response = await fetch(`${base}/v1/invoices/${resource}`, {
      method, headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), ...headers, Connection: 'close' },
      signal: AbortSignal.timeout(3000), redirect: 'error',
    });
    return { status: response.status, body: await response.json() };
  };
  try {
    for (const c of fixture.cases) {
      const method = c.operation === 'readInvoice' ? 'GET' : 'PATCH';
      const observed = await request(c.resource, method, `demo-${c.account}`);
      const allowed = observed.status === 200 && observed.body.id === c.resource &&
        (method === 'GET' || observed.body.note === `fictional update by ${c.account}`);
      const denied = observed.status === 403 && !('id' in observed.body) && !('tenant' in observed.body);
      observations.push({ mode, caseId: c.id, account: c.account, resource: c.resource,
        method, expected: c.expected, requestPath: `/v1/invoices/${c.resource}`,
        observed, expectationMet: c.expected === 'allow' ? allowed : denied });
    }
    if (mode === 'tenant_and_role_checked') {
      controls.push({ name: 'no_demo_token', ...(await request('invoiceA', 'GET')) });
      controls.push({ name: 'forged_tenant_header', ...(await request('invoiceB', 'GET', 'demo-viewerA', { 'X-Tenant-Id': 'tenantB' })) });
    }
  } finally {
    server.closeAllConnections();
    await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
  }
}
const result = {
  schemaVersion: 1, fictional: true, testedAt: new Date().toISOString(), nodeVersion: process.version,
  scope: 'local_loopback_fixture_only', authentication: 'mock_demo_tokens',
  fixtureSha256: createHash('sha256').update(JSON.stringify(fixture)).digest('hex'),
  summary: {
    casesPerMode: fixture.cases.length,
    beforeViolations: observations.filter(o => o.mode === 'missing_authorisation' && !o.expectationMet).length,
    afterExpectationsMet: observations.filter(o => o.mode === 'tenant_and_role_checked' && o.expectationMet).length,
    controlRequests: controls.length,
  }, observations, controls,
};
console.log(JSON.stringify(result, null, 2));
if (result.summary.beforeViolations !== 4 || result.summary.afterExpectationsMet !== fixture.cases.length ||
    controls[0].status !== 401 || controls[1].status !== 403) process.exitCode = 1;
