import { describe, it } from 'node:test';
import { strict as assert } from 'node:assert';

import { MatrixActor } from '@open-matrix/core/core/MatrixActor.js';
import { RequestReply } from '@open-matrix/core/engine/remoting/RequestReply.js';
import { createRunnerRuntimeHandle } from '../../src/utils/runner-runtime.js';

class FactoryProbeActor extends MatrixActor {}

describe('runner runtime security policy', () => {
  it('starts production runner runtimes with standard policy and dynamic compilation disabled', async () => {
    const handle = await createRunnerRuntimeHandle('COM.TEST.RUNNER-POLICY');
    try {
      assert.equal(handle.runtime.isDynamicCompilationAllowed(), false);

      const rootContext = handle.runtime.getRootContext();
      const policyEngine = rootContext.securityRealm?.policyEngine;
      assert.ok(policyEngine, 'runner runtime should install a policy engine');
      assert.equal(
        policyEngine.evaluate({
          op: 'factory.create-from-code',
          payload: {},
          sender: 'test.probe',
          meta: { topic: 'factory-probe.$inbox', ts: Date.now() },
        }).action,
        'deny',
      );

      const actor = new FactoryProbeActor();
      await actor.initialize(rootContext.derive('factory-probe'), 'factory-probe');

      await assert.rejects(
        () => RequestReply.execute(
          rootContext,
          'factory-probe',
          'factory.create-from-code',
          { name: 'probe', code: 'class Probe extends MatrixActor {}' },
          { timeoutMs: 1_000 },
        ),
        /Dynamic component compilation denied by standard policy/,
      );
    } finally {
      await handle.shutdown();
    }
  });
});
