/**
 * AS/PLATFORM/2026/003 T001 — proof-harness NEW-HELPER acceptance.
 *
 * Demonstrates the two helpers T003/T004 need, each with a SEEDED-GAP leg AND a
 * KNOWN-GOOD-CONTROL leg (Rule 18 paired; the T001 acceptance gate):
 *
 *   1. rlsPairedProbe — generic per-table RLS-behavioral driver (T004). Probes a
 *      self-created scratch table as the aegis_app RLS-subject role (withTenantRls):
 *        • GAP  : RLS DISABLED  → a foreign tenant CAN read the owner's row →
 *                 the helper reports pass=false, foreignDenied=false (gap caught).
 *        • GOOD : RLS ENABLED + tenant_isolation policy → owner sees its row,
 *                 foreign tenant denied → helper reports pass=true.
 *
 *   2. keyClient — header-credential (Bearer) client (T003 machine-key auth-surface
 *      proof primitive). Drives an EXISTING scoped examiner-bearer route
 *      (/api/examiner/status, scope read:status — no tenant-resolution dependency,
 *      so the paired control isolates exactly the header-auth round-trip):
 *        • GAP  : a garbage Bearer token → 401 (auth refused).
 *        • GOOD : a freshly-minted valid scoped examiner token → 200.
 *
 * Self-contained: the scratch table is DROPped and the examiner token DELETEd in a
 * finally block (Rule 11 — only self-created scratch state, never existing data).
 * Runs against the live dev server on 127.0.0.1:5000. Exit 0 iff ALL legs PASS.
 */

import {
  ProofRun,
  verdict,
  rlsPairedProbe,
  keyClient,
  ownerPool,
  endOwnerPool,
  randomUUID,
} from "./lib/proof-harness";
import { issueExaminerToken } from "../server/lib/pilot-readiness-extras-9";

const RUN = Date.now();
const SCRATCH = `_kit_rls_probe_${RUN}`;
const OWNER_TENANT = `kit-owner-${RUN}`;
const FOREIGN_TENANT = `kit-foreign-${RUN}`;

async function main(): Promise<void> {
  const run = new ProofRun(
    "AS/PLATFORM/2026/003 T001 — proof-harness new-helper acceptance",
    "DEV",
  );
  const o = ownerPool();
  const rowId = randomUUID();
  let tokenId: string | null = null;

  try {
    // ── scratch table (owner DDL) + grant the aegis_app RLS-subject role SELECT ─
    await o.query(`CREATE TABLE "${SCRATCH}" (id varchar PRIMARY KEY, tenant_id varchar NOT NULL)`);
    await o.query(`GRANT SELECT ON "${SCRATCH}" TO aegis_app`);
    await o.query(`INSERT INTO "${SCRATCH}" (id, tenant_id) VALUES ($1, $2)`, [rowId, OWNER_TENANT]);

    // ── LEG 1 (rlsPairedProbe / SEEDED GAP) — RLS disabled → foreign reads row ──
    const gap = await rlsPairedProbe(SCRATCH, rowId, OWNER_TENANT, FOREIGN_TENANT);
    const gapCaught = gap.ownerExists && gap.ownerVisible && !gap.foreignDenied && !gap.pass;
    run.leg({
      id: "KIT-RLS-GAP",
      scenario: "rlsPairedProbe on an RLS-DISABLED scratch table (seeded gap)",
      expectation:
        "helper flags the gap: ownerExists & ownerVisible true, foreignDenied false, pass false",
      observed: `ownerExists=${gap.ownerExists} ownerVisible=${gap.ownerVisible}(n=${gap.ownerVisibleCount}) foreignDenied=${gap.foreignDenied}(n=${gap.foreignVisibleCount}) pass=${gap.pass}`,
      verdict: gapCaught
        ? verdict.verified("foreign tenant read the owner's row as aegis_app → gap surfaced")
        : verdict.fail(),
      pass: gapCaught,
      signals: { ...gap },
    });

    // ── enable RLS + tenant_isolation policy (the fix) ─────────────────────────
    await o.query(`ALTER TABLE "${SCRATCH}" ENABLE ROW LEVEL SECURITY`);
    await o.query(
      `CREATE POLICY tenant_isolation ON "${SCRATCH}" USING (tenant_id = current_tenant_id()) WITH CHECK (tenant_id = current_tenant_id())`,
    );

    // ── LEG 2 (rlsPairedProbe / KNOWN-GOOD CONTROL) — RLS enforced ─────────────
    const good = await rlsPairedProbe(SCRATCH, rowId, OWNER_TENANT, FOREIGN_TENANT);
    const isolated = good.ownerExists && good.ownerVisible && good.foreignDenied && good.pass;
    run.leg({
      id: "KIT-RLS-GOOD",
      scenario: "rlsPairedProbe on an RLS-ENABLED scratch table (known-good control)",
      expectation:
        "helper confirms isolation: owner sees row (n>=1), foreign denied (n=0), pass true",
      observed: `ownerVisible=${good.ownerVisible}(n=${good.ownerVisibleCount}) foreignDenied=${good.foreignDenied}(n=${good.foreignVisibleCount}) pass=${good.pass}`,
      verdict: isolated
        ? verdict.verified(
            "owner sees its row, foreign tenant denied — both as aegis_app under withTenantRls",
          )
        : verdict.fail(),
      pass: isolated,
      signals: { ...good },
    });

    // ── mint a valid examiner token for the keyClient known-good control ───────
    const minted = (await issueExaminerToken({
      examinerName: "kit-helper-demo",
      examinerEmail: `kit-helper-${RUN}@test.local`,
      scopes: ["read:status"],
      ttlHours: 1,
      issuedBy: "AS/PLATFORM/2026/003-T001-kit-demo",
    })) as { id: string; rawToken: string };
    tokenId = minted.id;

    // ── LEG 3 (keyClient / SEEDED GAP) — garbage Bearer → 401 ──────────────────
    const badKey = keyClient(`garbage-${randomUUID()}`);
    const bad = await badKey.get("/api/examiner/status");
    const gapAuth = bad.status === 401;
    run.leg({
      id: "KIT-KEY-GAP",
      scenario: "keyClient drives the scoped examiner route (read:status) with a GARBAGE bearer (seeded gap)",
      expectation: "401 — the primitive carried the header and the route refused the bad credential",
      observed: `HTTP ${bad.status} ${JSON.stringify(bad.json).slice(0, 100)}`,
      verdict: gapAuth
        ? verdict.verified("garbage Bearer → 401 via keyClient-injected Authorization header")
        : verdict.fail(),
      pass: gapAuth,
      signals: { status: bad.status },
    });

    // ── LEG 4 (keyClient / KNOWN-GOOD CONTROL) — valid scoped token → 200 ──────
    const goodKey = keyClient(minted.rawToken);
    const ok = await goodKey.get("/api/examiner/status");
    const goodAuth = ok.status === 200;
    run.leg({
      id: "KIT-KEY-GOOD",
      scenario:
        "keyClient drives the scoped examiner route (read:status) with a VALID minted token (known-good control)",
      expectation: "200 — the primitive's Bearer header authenticated the real scoped route",
      observed: `HTTP ${ok.status} ${JSON.stringify(ok.json).slice(0, 80)}`,
      verdict: goodAuth
        ? verdict.verified("valid read:status Bearer minted via issueExaminerToken → 200 via keyClient")
        : verdict.fail(),
      pass: goodAuth,
      signals: { status: ok.status },
    });
  } finally {
    // ── teardown (Rule 11: only self-created scratch state) ────────────────────
    if (tokenId) {
      await o.query("DELETE FROM examiner_tokens WHERE id = $1", [tokenId]).catch(() => {});
    }
    await o.query(`DROP TABLE IF EXISTS "${SCRATCH}" CASCADE`).catch(() => {});
  }

  run.report();
  const { allPass } = run.acceptance();
  await endOwnerPool();
  process.exit(allPass ? 0 : 1);
}

main().catch((e) => {
  console.error("FATAL", e);
  process.exit(1);
});
