/**
 * Platform Verification Plan — ref AS/AEGIS-CYBER/VERIFY/2026/001
 * VF-S7 (JIT — silent-failure sweep module): JIT-access fire-and-forget
 * durable-write loss — STEP-4 POST-FIX DEMONSTRATION (paired controls).
 *
 * STATUS: post-fix (T004). The VF-S7 fix is NOW APPLIED:
 *   - jit-access.ts: tenant-threaded, savepoint-contained `persistJitWrite` +
 *     fail-closed drop + observable counters; requestAccess assigns grant.tenantId
 *     once; approve/deny/revoke/recordAction verify tenant via `sameTenant`
 *     (cross-tenant attempt refused + counted, Finding 2); the 4 fire-and-forget
 *     `JitDB.saveJitGrant(grant).catch(()=>{})` sinks are replaced by awaited
 *     persistJitWrite; routes are async and thread { tenantId: req.tenantId, res }.
 *   - jit-access-db.ts: saveJitGrant gained an optional `runner` param so the
 *     write joins the request's pinned tx (the savepoint), not a fresh pool client.
 *
 * This script exercises the REAL fixed async manager methods on a FAITHFUL
 * request harness (architect Finding 1): runRequestPhaseTx mirrors
 * tenantMiddleware — a Drizzle .transaction() yielding a real PgTransaction in the
 * same AsyncLocalStorage the middleware uses, so the fix's nested db.transaction()
 * resolves to a genuine SAVEPOINT on that connection — the exact production
 * mechanism (NOT a manual BEGIN, NOT a second connection).
 *
 * Legs (Rule 18 — every denial assertion is interlocked with a positive one):
 *   F1  LAND (positive) — real requestAccess with the authorized tenant T_A →
 *       grant row LANDS durable AND tenant-correct (tenant_id = T_A).
 *   F2  COLLATERAL-SURVIVAL (the cure; inverse of the pre-fix "disease") — in ONE
 *       request tx under GUC=T_A: (a) a legit co-write (raw saveJitGrant, tenant
 *       T_A) AND (b) the real requestAccess with the WRONG tenant T_B (≠ GUC) →
 *       42501 inside its savepoint. The fix CONTAINS it: persistFailures +1, the
 *       broken grant row is absent, the legit co-write SURVIVES the COMMIT, the
 *       outer tx commits clean. (Pre-fix this destroyed the co-write — Mode A.)
 *   F3  FAIL-CLOSED (negative) — real requestAccess with tenant "default" (the
 *       real pre-Operation-2 resolution) → write DROPPED, NO NULL/garbage row,
 *       persistDroppedNoTenant +1. Method still returns in-memory success.
 *   F-RA recordAction LAND (positive; the folded recordAction-loss case) — record
 *       an action on F1's grant under T_A → durable actions_used 0 → 1.
 *   F-XT CROSS-TENANT REFUSED (negative; Finding 2) — attempt revoke of F1's
 *       (T_A) grant with actor tenant T_B → refused (success=false), grant stays
 *       ACTIVE in memory AND durable, persistDroppedTenantMismatch +1.
 *
 * Counters are read via jitAccessManager.getStats().persistence (the same surface
 * the admin-gated GET /api/jit/stats exposes).
 *
 * Connections:
 *   - owner = pg.Pool on DATABASE_URL (dev owner; bypasses RLS; out-of-band
 *     observer for count/tenant/status/actions + cleanup).
 *   - real path = imported JitDB sinks + jitAccessManager singleton via the module
 *     `db` proxy (appPool = aegis_app restricted role; RLS-enforced).
 *
 * Run: npx tsx scripts/vf-s7-jit-postfix-demonstration.ts   (DEV only)
 */

import pg from "pg";
import { sql } from "drizzle-orm";
import {
  appPool,
  tenantContext,
  makeClientRunner,
  type DrizzleDb,
} from "../server/db";
import * as JitDB from "../server/lib/jit-access-db";
import { jitAccessManager } from "../server/lib/jit-access";

const owner = new pg.Pool({ connectionString: process.env.DATABASE_URL });

const T_A = "vf-s7-pf-tenant-A";
const T_B = "vf-s7-pf-tenant-B"; // valid-looking, but != the GUC → induced 42501
const USER_PREFIX = "vf-s7-pf-"; // every row this script can create carries this
const base = Date.now();
const CO_ID = `VF-S7-PF-COWRITE-${base}`;

const errStr = (e: any) => `${e?.code ?? ""} ${e?.message ?? String(e)}`.trim();

async function countGrant(id: string): Promise<number> {
  if (!id) return -1;
  const r = await owner.query<{ n: string }>(
    "SELECT count(*)::int AS n FROM jit_grants WHERE id = $1",
    [id],
  );
  return Number(r.rows[0].n);
}
async function tenantOfGrant(id: string): Promise<string | null> {
  const r = await owner.query<{ t: string | null }>(
    "SELECT tenant_id AS t FROM jit_grants WHERE id = $1",
    [id],
  );
  return r.rows[0]?.t ?? null;
}
async function statusOfGrant(id: string): Promise<string | null> {
  const r = await owner.query<{ s: string | null }>(
    "SELECT status AS s FROM jit_grants WHERE id = $1",
    [id],
  );
  return r.rows[0]?.s ?? null;
}
async function actionsUsedOfGrant(id: string): Promise<number | null> {
  const r = await owner.query<{ a: number | null }>(
    "SELECT actions_used AS a FROM jit_grants WHERE id = $1",
    [id],
  );
  return r.rows[0]?.a ?? null;
}

/** Raw co-write payload in the exact shape saveJitGrant expects (the legit,
 *  tenant-correct write that must SURVIVE the F2 induced failure). */
function coWritePayload(id: string, tenantId: string) {
  const now = new Date();
  return {
    id,
    userId: `${USER_PREFIX}cowrite`,
    username: "VF-S7 PF co-write",
    originalRole: "auditor",
    elevatedRole: "auditor",
    reason: "vf-s7 post-fix co-write sentinel",
    status: "active",
    policyId: "auditor-elevation",
    resources: ["audit-logs"],
    actions: ["read"],
    actionsUsed: 0,
    auditLog: [{ timestamp: now, action: "requested", details: "vf-s7-pf" }],
    expiresAt: new Date(now.getTime() + 3_600_000),
    grantedAt: now,
    tenantId,
  };
}

interface PhaseDiag {
  commitCommand: string; // "COMMIT" = clean; "ROLLBACK" = tx poisoned/aborted
  phaseErr: string;
}

/** FAITHFUL request runtime — mirrors tenantMiddleware. A Drizzle .transaction()
 *  on a single pinned appPool client yields a REAL PgTransaction; we set the LOCAL
 *  tenant GUC inside it and stash the PgTransaction in the same AsyncLocalStorage
 *  the middleware uses. The fix's nested db.transaction() therefore resolves to a
 *  genuine SAVEPOINT on this connection. Drizzle COMMITs when the callback returns
 *  and ROLLBACKs if it throws. */
async function runRequestPhaseTx(
  tenantId: string,
  fn: (tx: DrizzleDb) => Promise<void>,
): Promise<PhaseDiag> {
  const client = await appPool.connect();
  const diag: PhaseDiag = { commitCommand: "", phaseErr: "" };
  try {
    const tdb = makeClientRunner(client);
    try {
      await tdb.transaction(async (tx) => {
        await tx.execute(
          sql`SELECT set_config('app.current_tenant_id', ${tenantId}, true)`,
        );
        await tenantContext.run(
          { runner: tx as unknown as DrizzleDb, tenantId },
          () => fn(tx as unknown as DrizzleDb),
        );
      });
      diag.commitCommand = "COMMIT";
    } catch (e: any) {
      diag.phaseErr = errStr(e);
      diag.commitCommand = "ROLLBACK";
    }
  } finally {
    client.release();
  }
  return diag;
}

interface Row {
  leg: string;
  scenario: string;
  expectation: string;
  observed: string;
  verdict: "PASS" | "FAIL";
}
const rows: Row[] = [];
const record = (r: Row) => rows.push(r);

function persistSnapshot() {
  return { ...jitAccessManager.getStats().persistence };
}

async function cleanup() {
  await owner.query("DELETE FROM jit_grants WHERE id = $1", [CO_ID]);
  await owner.query("DELETE FROM jit_grants WHERE user_id LIKE $1", [
    `${USER_PREFIX}%`,
  ]);
}

async function main() {
  console.log("=== VF-S7 JIT POST-FIX DEMONSTRATION (paired controls) ===\n");
  await cleanup(); // start from a clean slate (idempotent re-run)

  let f1Id = "";
  let f2BrokenId = "";

  // ---- F1: LAND (positive) — real requestAccess with authorized tenant T_A ----
  {
    const before = persistSnapshot();
    const diag = await runRequestPhaseTx(T_A, async () => {
      const r = await jitAccessManager.requestAccess(
        `${USER_PREFIX}u1`,
        "VF-S7 PF U1",
        "auditor",
        "auditor-elevation",
        "vf-s7-pf F1 land",
        undefined,
        undefined,
        { tenantId: T_A },
      );
      if (r.success && r.grant) f1Id = r.grant.id;
    });
    const after = persistSnapshot();
    const cnt = await countGrant(f1Id);
    const ten = await tenantOfGrant(f1Id);
    const pass =
      diag.commitCommand === "COMMIT" &&
      cnt === 1 &&
      ten === T_A &&
      after.persistFailures === before.persistFailures &&
      after.persistDroppedNoTenant === before.persistDroppedNoTenant;
    record({
      leg: "F1",
      scenario: "real requestAccess, authorized tenant T_A",
      expectation: "row LANDS durable + tenant_id=T_A; clean COMMIT; no counters",
      observed: `commit=${diag.commitCommand} count=${cnt} tenant=${ten} dropNoTenantΔ=${after.persistDroppedNoTenant - before.persistDroppedNoTenant} failΔ=${after.persistFailures - before.persistFailures}`,
      verdict: pass ? "PASS" : "FAIL",
    });
  }

  // ---- F2: COLLATERAL-SURVIVAL (the cure) — co-write survives an induced fail --
  {
    const before = persistSnapshot();
    const diag = await runRequestPhaseTx(T_A, async (tx) => {
      // (a) legit, tenant-correct co-write (must SURVIVE)
      await JitDB.saveJitGrant(coWritePayload(CO_ID, T_A), tx);
      // (b) induced failure: requestAccess with WRONG tenant T_B vs GUC=T_A →
      //     savepoint INSERT violates RLS WITH CHECK → 42501, contained.
      const r = await jitAccessManager.requestAccess(
        `${USER_PREFIX}u2`,
        "VF-S7 PF U2",
        "auditor",
        "auditor-elevation",
        "vf-s7-pf F2 induced-fail",
        undefined,
        undefined,
        { tenantId: T_B },
      );
      if (r.success && r.grant) f2BrokenId = r.grant.id;
    });
    const after = persistSnapshot();
    const coCnt = await countGrant(CO_ID);
    const coTen = await tenantOfGrant(CO_ID);
    const brokenCnt = await countGrant(f2BrokenId);
    const pass =
      diag.commitCommand === "COMMIT" &&
      coCnt === 1 &&
      coTen === T_A &&
      brokenCnt === 0 &&
      after.persistFailures === before.persistFailures + 1;
    record({
      leg: "F2",
      scenario: "ONE tx (GUC=T_A): legit co-write + requestAccess wrong tenant T_B",
      expectation:
        "co-write SURVIVES (count=1,T_A); broken absent (count=0); persistFailures +1; outer COMMIT",
      observed: `commit=${diag.commitCommand} coWrite=${coCnt}/${coTen} broken=${brokenCnt} failΔ=${after.persistFailures - before.persistFailures} phaseErr='${diag.phaseErr}'`,
      verdict: pass ? "PASS" : "FAIL",
    });
  }

  // ---- F3: FAIL-CLOSED (negative) — requestAccess tenant "default" → dropped ---
  {
    const before = persistSnapshot();
    let f3Id = "";
    let methodSuccess = false;
    const r = await jitAccessManager.requestAccess(
      `${USER_PREFIX}u3`,
      "VF-S7 PF U3",
      "auditor",
      "auditor-elevation",
      "vf-s7-pf F3 fail-closed",
      undefined,
      undefined,
      { tenantId: "default" },
    );
    methodSuccess = r.success;
    if (r.grant) f3Id = r.grant.id;
    const after = persistSnapshot();
    const cnt = await countGrant(f3Id);
    const pass =
      methodSuccess === true &&
      cnt === 0 &&
      after.persistDroppedNoTenant === before.persistDroppedNoTenant + 1 &&
      after.persistFailures === before.persistFailures;
    record({
      leg: "F3",
      scenario: 'real requestAccess, tenant "default" (pre-Op-2 resolution)',
      expectation:
        "NO row (count=0); persistDroppedNoTenant +1; method still returns success",
      observed: `methodSuccess=${methodSuccess} count=${cnt} dropNoTenantΔ=${after.persistDroppedNoTenant - before.persistDroppedNoTenant}`,
      verdict: pass ? "PASS" : "FAIL",
    });
  }

  // ---- F-RA: recordAction LAND (positive; folded recordAction-loss case) ------
  {
    const before = persistSnapshot();
    const beforeActions = await actionsUsedOfGrant(f1Id);
    const diag = await runRequestPhaseTx(T_A, async () => {
      await jitAccessManager.recordAction(f1Id, "read", "audit-logs", "127.0.0.1", {
        tenantId: T_A,
      });
    });
    const after = persistSnapshot();
    const afterActions = await actionsUsedOfGrant(f1Id);
    const pass =
      diag.commitCommand === "COMMIT" &&
      beforeActions === 0 &&
      afterActions === 1 &&
      after.persistFailures === before.persistFailures;
    record({
      leg: "F-RA",
      scenario: "recordAction on F1 grant (T_A) — the folded recordAction-loss case",
      expectation: "durable actions_used 0 → 1; clean COMMIT; no failures",
      observed: `commit=${diag.commitCommand} actions_used ${beforeActions}→${afterActions} failΔ=${after.persistFailures - before.persistFailures}`,
      verdict: pass ? "PASS" : "FAIL",
    });
  }

  // ---- F-XT: CROSS-TENANT REFUSED (negative; Finding 2) -----------------------
  {
    const before = persistSnapshot();
    const r = await jitAccessManager.revokeAccess(f1Id, `${USER_PREFIX}attacker`, "xt", {
      tenantId: T_B,
    });
    const after = persistSnapshot();
    const memGrant = jitAccessManager.getActiveGrant(`${USER_PREFIX}u1`);
    const durableStatus = await statusOfGrant(f1Id);
    const pass =
      r.success === false &&
      after.persistDroppedTenantMismatch ===
        before.persistDroppedTenantMismatch + 1 &&
      memGrant !== undefined &&
      memGrant.status === "active" &&
      durableStatus === "active";
    record({
      leg: "F-XT",
      scenario: "revoke F1 grant (owned T_A) with actor tenant T_B (cross-tenant)",
      expectation:
        "REFUSED (success=false); grant stays ACTIVE (mem+durable); mismatch +1",
      observed: `success=${r.success} err='${r.error}' mismatchΔ=${after.persistDroppedTenantMismatch - before.persistDroppedTenantMismatch} memStatus=${memGrant?.status ?? "MISSING"} durableStatus=${durableStatus}`,
      verdict: pass ? "PASS" : "FAIL",
    });
  }

  // ---- report ----
  console.log(
    "LEG   VERDICT  SCENARIO / EXPECTATION / OBSERVED\n" +
      "----  -------  ----------------------------------------------------------",
  );
  for (const r of rows) {
    console.log(
      `${r.leg.padEnd(4)}  ${r.verdict.padEnd(7)}  ${r.scenario}\n` +
        `                 expect: ${r.expectation}\n` +
        `                 observe: ${r.observed}\n`,
    );
  }
  const allPass = rows.every((r) => r.verdict === "PASS");
  console.log(
    `\nfinal persistence counters: ${JSON.stringify(persistSnapshot())}`,
  );
  console.log(`\nOVERALL: ${allPass ? "PASS — all legs" : "FAIL — see above"}`);

  await cleanup();
  await owner.end();
  process.exit(allPass ? 0 : 1);
}

main().catch(async (e) => {
  console.error("FATAL", e);
  try {
    await cleanup();
    await owner.end();
  } catch {}
  process.exit(2);
});
