// Audit Class 3 — core-banking gateway fail-closed fence.
//
// The CBS gateway was the one connector with no fail-closed fence: it ran a local
// simulator and returned status:"SUCCESS" + a fabricated cbsReference for a freeze/
// reversal that never reached Finacle/Flexcube/T24 (H5), and that fabricated SUCCESS
// was written to the tamper-evident audit chain (M3). The fix gates simulateCBSCall:
// without a wired CBS (CBS_ENDPOINT_URL) and outside an explicit non-prod CBS_DEMO_MODE,
// it throws NOT_CONFIGURED, so every operation fails closed (status:"FAILED", no
// fabricated reference, no kill-switch, no audit entry).
//
// In-memory gateway — no DB required.

import { test, describe, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import { coreBankingGateway } from "../server/lib/core-banking-gateway.js";

function clearCbsEnv() {
  delete process.env.CBS_ENDPOINT_URL;
  delete process.env.CBS_DEMO_MODE;
}

describe("Audit Class 3 — CBS gateway fail-closed fence", () => {
  beforeEach(clearCbsEnv);
  afterEach(clearCbsEnv);

  test("H5: without a wired CBS, freezeAccount fails closed — no fabricated SUCCESS or reference", async () => {
    const r = await coreBankingGateway.freezeAccount("ACC-TEST-1", "audit-test", "tester", "finacle");
    assert.notEqual(r.status, "SUCCESS", "must NOT fabricate SUCCESS without a real CBS");
    assert.ok(!r.cbsReference, `must NOT mint a fabricated CBS reference; got ${r.cbsReference}`);
    assert.match(String(r.error ?? ""), /NOT_CONFIGURED/, "error must say the CBS is not configured");
  });

  test("H5: reverseTransaction also fails closed", async () => {
    const r = await coreBankingGateway.reverseTransaction("TXN-TEST-1", "audit-test", "tester", "finacle");
    assert.notEqual(r.status, "SUCCESS", "must NOT fabricate a reversal SUCCESS");
    assert.ok(!r.cbsReference, "must NOT mint a fabricated reference");
  });

  test("L: without a wired CBS, checkCBSHealth reports unhealthy (no fabricated 'healthy:true')", async () => {
    const h = await coreBankingGateway.checkCBSHealth("finacle");
    assert.equal(h.healthy, false, "must NOT fabricate healthy:true without a real CBS");
  });

  test("demo path intact: explicit non-prod CBS_DEMO_MODE bypasses the not-configured fence", async () => {
    process.env.CBS_DEMO_MODE = "true"; // NODE_ENV is not 'production' under test
    const r = await coreBankingGateway.freezeAccount("ACC-TEST-2", "audit-test", "tester", "finacle");
    // The simulator runs (SUCCESS, or a 2% random CBS_TIMEOUT) — but NEVER the NOT_CONFIGURED fence.
    assert.doesNotMatch(String(r.error ?? ""), /NOT_CONFIGURED/, "demo mode must bypass the not-configured fence");
  });
});
