/**
 * AS/PLATFORM/2026/008 — Tenant-Sep Chunk B behavioral verification (TS-B4).
 *
 * Tables newly tenant-isolated this chunk (register §W9-SYNTHESIS P-B no-tenant-column
 * SECURITY class), in 3 groups:
 *   Group 1 — webhook pair:
 *     webhook_configs        (writer: storage.createWebhook              — schema.ts)
 *     webhook_logs           (writer: storage.logWebhookExecution        — schema.ts)
 *   Group 2 — threat-intel triad:
 *     threat_feeds           (writer: threat-intelligence-db.saveFeed     — schema-persistence.ts)
 *     threat_indicators      (writer: threat-intelligence-db.saveIndicator— schema-persistence.ts)
 *     threat_feed_sync_log   (writer: threat-intel-sync.syncFeedToDb       — schema-persistence.ts)
 *   Group 3 — biometric:
 *     biometric_profiles     (writer: wave-final-services.saveBiometricProfile — schema-final.ts)
 *
 * Each table now (a) has a DB NOT NULL tenant_id text column, (b) is RLS-enrolled
 * (ENABLE RLS + policy USING/WITH CHECK tenant_id = current_tenant_id()), and
 * (c) has a fail-closed writer that refuses an unbound write.
 *
 * Per table, paired POS/NEG (Rule 18), as the RLS-subject role aegis_app:
 *   L1 POS  : write own-tenant row (tenant A) via the real writer → readable by A.
 *   L2 NEG  : RLS USING — tenant B does NOT see tenant A's row.
 *   L3 NEG  : RLS WITH CHECK — a write carrying tenant_id=B under GUC=A → REJECTED (42501).
 *             webhook pair drives this through the REAL writer (createWebhook /
 *             logWebhookExecution accept a tenantId arg). The triad + biometric
 *             writers set the GUC = tenantId internally (GUC-self-consistent by
 *             construction, so a foreign-tenant write cannot reach the writer), so
 *             their L3 is the DB belt — a direct insert with tenant_id=B under GUC=A.
 *   L4 NEG  : writer fail-closed — no tenant_id → the writer's own guard throws
 *             BEFORE any DB call (asserted by "tenantId is required").
 *   L5 NEG  : DB belt — a direct insert with tenant_id=NULL is REJECTED by the DB
 *             (NOT NULL + WITH CHECK), so even a future unguarded writer cannot
 *             persist a null-tenant row.
 *
 * Code-read write-site note (not behaviorally driven here): threat_feed_sync_log's
 * only insert sites are inside syncFeedToDb's two withTenantRls blocks
 * (threat-intel-sync.ts:336-345 error path, :373-381 success path); both pass the
 * bound `tenantId` param unconditionally. L4 here drives syncFeedToDb's top-of-
 * function fail-closed guard (no network), L1-L3/L5 prove the table's RLS via belt.
 *
 * Role discipline (Rule 17): every DB-touching leg runs as aegis_app. Writers that
 * use the module `db` Proxy (webhook pair) run inside runAsTenant() — pins an appPool
 * client, sets the tenant GUC, and activates tenantContext so the Proxy resolves to
 * the GUC-set client (mirrors the request middleware). Writers that manage their own
 * tenant tx (saveFeed/saveIndicator/saveBiometricProfile via withTenantRls) also use
 * appPool = aegis_app. A0 asserts current_user='aegis_app' so the isolation proof is
 * not hollow-green (the owner role bypasses RLS). Synthetic, self-cleaning rows. NO
 * secret values are printed.
 *
 * Run: npx tsx scripts/vf-tsb4-tenant-sep-chunkB-proof.ts
 */
import { eq } from "drizzle-orm";
import { appPool, ddlPool, tenantContext, makeClientRunner, db } from "../server/db";
import { webhookConfigs, webhookLogs, type WebhookEventType } from "../shared/schema";
import { threatFeeds, threatIndicators, threatFeedSyncLog } from "../shared/schema-persistence";
import { biometricProfiles } from "../shared/schema-final";
import { storage } from "../server/storage";
import { saveFeed, saveIndicator } from "../server/lib/threat-intelligence-db";
import { syncFeedToDb } from "../server/lib/threat-intel-sync";
import { saveBiometricProfile } from "../server/lib/wave-final-services";

let pass = 0;
let fail = 0;
const lines: string[] = [];
function check(name: string, cond: boolean, detail = "") {
  if (cond) {
    pass++;
    lines.push(`  PASS  ${name}${detail ? ` — ${detail}` : ""}`);
  } else {
    fail++;
    lines.push(`  FAIL  ${name}${detail ? ` — ${detail}` : ""}`);
  }
}

// Replicate the request path so module-`db`-proxy code runs as aegis_app under
// the tenant GUC (mirrors tenant-middleware). withTenantRls does NOT activate
// tenantContext; this does.
async function runAsTenant<T>(tenantId: string, fn: () => Promise<T>): Promise<T> {
  const client = await appPool.connect();
  try {
    await client.query("BEGIN");
    await client.query("SELECT set_config('app.current_tenant_id', $1, true)", [tenantId]);
    const runner = makeClientRunner(client);
    const out = await tenantContext.run({ runner, tenantId }, fn);
    await client.query("COMMIT");
    return out;
  } catch (e) {
    try { await client.query("ROLLBACK"); } catch { /* noop */ }
    throw e;
  } finally {
    client.release();
  }
}

const MARK = "vf-tsb4";
const RLS_ERR = /42501|policy|row-level/i;
const NULL_ERR = /23502|42501|null|policy|row-level/i;
// Synthetic biometric user ids (integer PK; biometric_profiles is empty dev+prod).
const BIO_UID_POS = 990000041;
const BIO_UID_XT = 990000042;
const BIO_UID_NULL = 990000043;

async function main() {
  const tRows = (await appPool.query("SELECT id, slug FROM tenants ORDER BY slug")).rows as Array<{ id: string; slug: string }>;
  const tenantA = tRows.find((r) => r.slug === "aegis-sovereign")?.id;
  const tenantB = tRows.find((r) => r.slug === "stanbic-ug")?.id;
  if (!tenantA || !tenantB) throw new Error(`could not resolve tenants A/B from ${JSON.stringify(tRows)}`);

  lines.push("== A0. Role discipline — proofs run as the RLS-subject role, not the owner ==");
  const who = await runAsTenant(tenantA, async () =>
    (await db.execute(`SELECT current_user AS u`)) as any
  );
  const currentUser = (who.rows?.[0]?.u ?? who[0]?.u) as string;
  check(
    "A0 runAsTenant connects as aegis_app (non-bypass RLS-subject role) [role discipline]",
    currentUser === "aegis_app",
    `current_user=${currentUser}`,
  );

  // ── Group 1a: webhook_configs ────────────────────────────────────────────
  lines.push("== WC. webhook_configs — storage.createWebhook ==");
  const wcCfg = (tenantId: string, tag: string) => ({
    name: `${MARK}-${tag}`, integrationType: "CUSTOM", endpointUrl: "https://example.test/hook",
    events: "[]", tenantId,
  });

  // L1 POS
  const wcRow = await runAsTenant(tenantA, async () =>
    storage.createWebhook(wcCfg(tenantA, "wc") as any)
  );
  const wcSeenByA = await runAsTenant(tenantA, async () =>
    db.select().from(webhookConfigs).where(eq(webhookConfigs.id, wcRow.id))
  );
  check(
    "WC-L1 createWebhook(own tenant) persists + readable by owner [RLS POS]",
    wcSeenByA.length === 1 && wcSeenByA[0].tenantId === tenantA,
    `rows=${wcSeenByA.length} tenant matches A=${wcSeenByA[0]?.tenantId === tenantA}`,
  );

  // L2 NEG
  const wcSeenByB = await runAsTenant(tenantB, async () =>
    db.select().from(webhookConfigs).where(eq(webhookConfigs.id, wcRow.id))
  );
  check("WC-L2 tenant B does NOT see tenant A's webhook [RLS USING NEG]", wcSeenByB.length === 0, `tenantB rows=${wcSeenByB.length}`);

  // L3 NEG — real writer, foreign tenant under GUC=A
  let wcXt = false, wcXtErr = "";
  try {
    await runAsTenant(tenantA, async () => storage.createWebhook(wcCfg(tenantB, "wc-xt") as any));
  } catch (e: any) { wcXt = true; wcXtErr = String(e?.code ?? e?.message ?? e); }
  check("WC-L3 createWebhook tenant_id=B under GUC=A rejected [RLS WITH CHECK NEG]", wcXt && RLS_ERR.test(wcXtErr), `rejected=${wcXt} err=${wcXtErr}`);

  // L4 NEG — fail-closed guard
  let wcFc = false, wcFcMsg = "";
  try {
    await storage.createWebhook({ name: `${MARK}-wc-fc`, integrationType: "CUSTOM", endpointUrl: "https://example.test/hook", events: "[]" } as any);
  } catch (e: any) { wcFc = true; wcFcMsg = String(e?.message ?? e); }
  check("WC-L4 createWebhook without tenantId throws fail-closed guard [writer-binding NEG]", wcFc && /tenantId is required/i.test(wcFcMsg), `threw=${wcFc} msg=${wcFcMsg}`);

  // L5 NEG — DB belt null tenant
  let wcNull = false, wcNullErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      db.insert(webhookConfigs).values({ name: `${MARK}-wc-null`, integrationType: "CUSTOM", endpointUrl: "https://example.test/hook", events: "[]", tenantId: null as any })
    );
  } catch (e: any) { wcNull = true; wcNullErr = String(e?.code ?? e?.message ?? e); }
  check("WC-L5 direct NULL-tenant insert rejected by DB belt [NOT NULL + WITH CHECK NEG]", wcNull && NULL_ERR.test(wcNullErr), `rejected=${wcNull} err=${wcNullErr}`);

  // ── Group 1b: webhook_logs (FK → webhook_configs) ────────────────────────
  lines.push("== WL. webhook_logs — storage.logWebhookExecution (tenant derived from parent config) ==");
  // Parent config for tenant A (FK target for the log rows).
  const wcParent = await runAsTenant(tenantA, async () =>
    storage.createWebhook(wcCfg(tenantA, "wl-parent") as any)
  );
  const evt: WebhookEventType = "THREAT_DETECTED";

  // L1 POS
  const wlRow = await runAsTenant(tenantA, async () =>
    storage.logWebhookExecution({ tenantId: tenantA, webhookId: wcParent.id, eventType: evt, payload: `{"m":"${MARK}"}`, success: true })
  );
  const wlSeenByA = await runAsTenant(tenantA, async () =>
    db.select().from(webhookLogs).where(eq(webhookLogs.id, wlRow.id))
  );
  check("WL-L1 logWebhookExecution(own tenant) persists + readable by owner [RLS POS]", wlSeenByA.length === 1 && wlSeenByA[0].tenantId === tenantA, `rows=${wlSeenByA.length} tenant matches A=${wlSeenByA[0]?.tenantId === tenantA}`);

  // L2 NEG
  const wlSeenByB = await runAsTenant(tenantB, async () =>
    db.select().from(webhookLogs).where(eq(webhookLogs.id, wlRow.id))
  );
  check("WL-L2 tenant B does NOT see tenant A's webhook log [RLS USING NEG]", wlSeenByB.length === 0, `tenantB rows=${wlSeenByB.length}`);

  // L3 NEG — real writer, foreign tenant under GUC=A (FK parent belongs to A)
  let wlXt = false, wlXtErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      storage.logWebhookExecution({ tenantId: tenantB, webhookId: wcParent.id, eventType: evt, payload: "{}", success: true })
    );
  } catch (e: any) { wlXt = true; wlXtErr = String(e?.code ?? e?.message ?? e); }
  check("WL-L3 logWebhookExecution tenant_id=B under GUC=A rejected [RLS WITH CHECK NEG]", wlXt && RLS_ERR.test(wlXtErr), `rejected=${wlXt} err=${wlXtErr}`);

  // L4 NEG — fail-closed guard
  let wlFc = false, wlFcMsg = "";
  try {
    await storage.logWebhookExecution({ webhookId: wcParent.id, eventType: evt, payload: "{}", success: true } as any);
  } catch (e: any) { wlFc = true; wlFcMsg = String(e?.message ?? e); }
  check("WL-L4 logWebhookExecution without tenantId throws fail-closed guard [writer-binding NEG]", wlFc && /tenantId is required/i.test(wlFcMsg), `threw=${wlFc} msg=${wlFcMsg}`);

  // L5 NEG — DB belt null tenant
  let wlNull = false, wlNullErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      db.insert(webhookLogs).values({ webhookId: wcParent.id, eventType: evt, payload: "{}", success: true, tenantId: null as any })
    );
  } catch (e: any) { wlNull = true; wlNullErr = String(e?.code ?? e?.message ?? e); }
  check("WL-L5 direct NULL-tenant insert rejected by DB belt [NOT NULL + WITH CHECK NEG]", wlNull && NULL_ERR.test(wlNullErr), `rejected=${wlNull} err=${wlNullErr}`);

  // ── Group 2a: threat_feeds ───────────────────────────────────────────────
  lines.push("== TF. threat_feeds — threat-intelligence-db.saveFeed (own withTenantRls tx) ==");
  const tfFeed = (tag: string) => ({ id: `${MARK}-${tag}`, name: `${MARK}-${tag}`, type: "custom", url: "https://example.test/feed", enabled: true, refreshInterval: 60, lastSync: null as Date | null, indicatorCount: 0, status: "active" });

  // L1 POS
  await saveFeed(tfFeed("tf"), tenantA);
  const tfSeenByA = await runAsTenant(tenantA, async () =>
    db.select().from(threatFeeds).where(eq(threatFeeds.id, `${MARK}-tf`))
  );
  check("TF-L1 saveFeed(own tenant) persists + readable by owner [RLS POS]", tfSeenByA.length === 1 && tfSeenByA[0].tenantId === tenantA, `rows=${tfSeenByA.length} tenant matches A=${tfSeenByA[0]?.tenantId === tenantA}`);

  // L2 NEG
  const tfSeenByB = await runAsTenant(tenantB, async () =>
    db.select().from(threatFeeds).where(eq(threatFeeds.id, `${MARK}-tf`))
  );
  check("TF-L2 tenant B does NOT see tenant A's feed [RLS USING NEG]", tfSeenByB.length === 0, `tenantB rows=${tfSeenByB.length}`);

  // L3 NEG — DB belt: foreign tenant under GUC=A (writer is GUC-self-consistent)
  let tfXt = false, tfXtErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      db.insert(threatFeeds).values({ id: `${MARK}-tf-xt`, tenantId: tenantB, name: `${MARK}-tf-xt`, type: "custom", url: "https://example.test/feed" })
    );
  } catch (e: any) { tfXt = true; tfXtErr = String(e?.code ?? e?.message ?? e); }
  check("TF-L3 direct insert tenant_id=B under GUC=A rejected [RLS WITH CHECK NEG — DB belt]", tfXt && RLS_ERR.test(tfXtErr), `rejected=${tfXt} err=${tfXtErr}`);

  // L4 NEG — fail-closed guard
  let tfFc = false, tfFcMsg = "";
  try { await saveFeed(tfFeed("tf-fc"), ""); } catch (e: any) { tfFc = true; tfFcMsg = String(e?.message ?? e); }
  check("TF-L4 saveFeed without tenantId throws fail-closed guard [writer-binding NEG]", tfFc && /tenantId is required/i.test(tfFcMsg), `threw=${tfFc} msg=${tfFcMsg}`);

  // L5 NEG — DB belt null tenant
  let tfNull = false, tfNullErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      db.insert(threatFeeds).values({ id: `${MARK}-tf-null`, tenantId: null as any, name: `${MARK}-tf-null`, type: "custom", url: "https://example.test/feed" })
    );
  } catch (e: any) { tfNull = true; tfNullErr = String(e?.code ?? e?.message ?? e); }
  check("TF-L5 direct NULL-tenant insert rejected by DB belt [NOT NULL + WITH CHECK NEG]", tfNull && NULL_ERR.test(tfNullErr), `rejected=${tfNull} err=${tfNullErr}`);

  // ── Group 2b: threat_indicators ──────────────────────────────────────────
  lines.push("== TI. threat_indicators — threat-intelligence-db.saveIndicator (own withTenantRls tx) ==");
  const tiInd = (tag: string) => ({ id: `${MARK}-${tag}`, type: "ip", value: "203.0.113.7", severity: "medium", source: MARK, confidence: 50, tags: [] as string[], firstSeen: new Date(), lastSeen: new Date() });

  // L1 POS
  await saveIndicator(tiInd("ti"), tenantA);
  const tiSeenByA = await runAsTenant(tenantA, async () =>
    db.select().from(threatIndicators).where(eq(threatIndicators.id, `${MARK}-ti`))
  );
  check("TI-L1 saveIndicator(own tenant) persists + readable by owner [RLS POS]", tiSeenByA.length === 1 && tiSeenByA[0].tenantId === tenantA, `rows=${tiSeenByA.length} tenant matches A=${tiSeenByA[0]?.tenantId === tenantA}`);

  // L2 NEG
  const tiSeenByB = await runAsTenant(tenantB, async () =>
    db.select().from(threatIndicators).where(eq(threatIndicators.id, `${MARK}-ti`))
  );
  check("TI-L2 tenant B does NOT see tenant A's indicator [RLS USING NEG]", tiSeenByB.length === 0, `tenantB rows=${tiSeenByB.length}`);

  // L3 NEG — DB belt foreign tenant
  let tiXt = false, tiXtErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      db.insert(threatIndicators).values({ id: `${MARK}-ti-xt`, tenantId: tenantB, type: "ip", value: "203.0.113.8", source: MARK })
    );
  } catch (e: any) { tiXt = true; tiXtErr = String(e?.code ?? e?.message ?? e); }
  check("TI-L3 direct insert tenant_id=B under GUC=A rejected [RLS WITH CHECK NEG — DB belt]", tiXt && RLS_ERR.test(tiXtErr), `rejected=${tiXt} err=${tiXtErr}`);

  // L4 NEG — fail-closed guard
  let tiFc = false, tiFcMsg = "";
  try { await saveIndicator(tiInd("ti-fc"), ""); } catch (e: any) { tiFc = true; tiFcMsg = String(e?.message ?? e); }
  check("TI-L4 saveIndicator without tenantId throws fail-closed guard [writer-binding NEG]", tiFc && /tenantId is required/i.test(tiFcMsg), `threw=${tiFc} msg=${tiFcMsg}`);

  // L5 NEG — DB belt null tenant
  let tiNull = false, tiNullErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      db.insert(threatIndicators).values({ id: `${MARK}-ti-null`, tenantId: null as any, type: "ip", value: "203.0.113.9", source: MARK })
    );
  } catch (e: any) { tiNull = true; tiNullErr = String(e?.code ?? e?.message ?? e); }
  check("TI-L5 direct NULL-tenant insert rejected by DB belt [NOT NULL + WITH CHECK NEG]", tiNull && NULL_ERR.test(tiNullErr), `rejected=${tiNull} err=${tiNullErr}`);

  // ── Group 2c: threat_feed_sync_log ───────────────────────────────────────
  lines.push("== TFSL. threat_feed_sync_log — RLS belt + syncFeedToDb fail-closed guard ==");
  const tfslVals = (id: string, tenantId: string | null) => ({ id, tenantId: tenantId as any, feedId: `${MARK}-feed`, feedName: `${MARK}-feed`, status: "success", indicatorsAdded: 0, indicatorsUpdated: 0, durationMs: 1 });

  // L1 POS — DB belt as aegis_app (no standalone non-network writer; sites are in syncFeedToDb)
  await runAsTenant(tenantA, async () => db.insert(threatFeedSyncLog).values(tfslVals(`${MARK}-tfsl`, tenantA)));
  const tfslSeenByA = await runAsTenant(tenantA, async () =>
    db.select().from(threatFeedSyncLog).where(eq(threatFeedSyncLog.id, `${MARK}-tfsl`))
  );
  check("TFSL-L1 own-tenant sync-log row persists + readable by owner [RLS POS]", tfslSeenByA.length === 1 && tfslSeenByA[0].tenantId === tenantA, `rows=${tfslSeenByA.length} tenant matches A=${tfslSeenByA[0]?.tenantId === tenantA}`);

  // L2 NEG
  const tfslSeenByB = await runAsTenant(tenantB, async () =>
    db.select().from(threatFeedSyncLog).where(eq(threatFeedSyncLog.id, `${MARK}-tfsl`))
  );
  check("TFSL-L2 tenant B does NOT see tenant A's sync-log row [RLS USING NEG]", tfslSeenByB.length === 0, `tenantB rows=${tfslSeenByB.length}`);

  // L3 NEG — DB belt foreign tenant
  let tfslXt = false, tfslXtErr = "";
  try {
    await runAsTenant(tenantA, async () => db.insert(threatFeedSyncLog).values(tfslVals(`${MARK}-tfsl-xt`, tenantB)));
  } catch (e: any) { tfslXt = true; tfslXtErr = String(e?.code ?? e?.message ?? e); }
  check("TFSL-L3 direct insert tenant_id=B under GUC=A rejected [RLS WITH CHECK NEG — DB belt]", tfslXt && RLS_ERR.test(tfslXtErr), `rejected=${tfslXt} err=${tfslXtErr}`);

  // L4 NEG — real writer fail-closed guard (top of syncFeedToDb, before any network)
  let tfslFc = false, tfslFcMsg = "";
  try { await syncFeedToDb({ id: `${MARK}-feed`, name: `${MARK}-feed`, type: "custom" } as any, ""); } catch (e: any) { tfslFc = true; tfslFcMsg = String(e?.message ?? e); }
  check("TFSL-L4 syncFeedToDb without tenantId throws fail-closed guard [writer-binding NEG]", tfslFc && /tenantId is required/i.test(tfslFcMsg), `threw=${tfslFc} msg=${tfslFcMsg}`);

  // L5 NEG — DB belt null tenant
  let tfslNull = false, tfslNullErr = "";
  try {
    await runAsTenant(tenantA, async () => db.insert(threatFeedSyncLog).values(tfslVals(`${MARK}-tfsl-null`, null)));
  } catch (e: any) { tfslNull = true; tfslNullErr = String(e?.code ?? e?.message ?? e); }
  check("TFSL-L5 direct NULL-tenant insert rejected by DB belt [NOT NULL + WITH CHECK NEG]", tfslNull && NULL_ERR.test(tfslNullErr), `rejected=${tfslNull} err=${tfslNullErr}`);

  // ── Group 3: biometric_profiles ──────────────────────────────────────────
  lines.push("== BP. biometric_profiles — wave-final-services.saveBiometricProfile (own withTenantRls tx) ==");

  // L1 POS
  await saveBiometricProfile({ userId: BIO_UID_POS, sampleCount: 5, confidenceScore: 0.9 }, tenantA);
  const bpSeenByA = await runAsTenant(tenantA, async () =>
    db.select().from(biometricProfiles).where(eq(biometricProfiles.userId, BIO_UID_POS))
  );
  check("BP-L1 saveBiometricProfile(own tenant) persists + readable by owner [RLS POS]", bpSeenByA.length === 1 && bpSeenByA[0].tenantId === tenantA, `rows=${bpSeenByA.length} tenant matches A=${bpSeenByA[0]?.tenantId === tenantA}`);

  // L2 NEG
  const bpSeenByB = await runAsTenant(tenantB, async () =>
    db.select().from(biometricProfiles).where(eq(biometricProfiles.userId, BIO_UID_POS))
  );
  check("BP-L2 tenant B does NOT see tenant A's biometric profile [RLS USING NEG]", bpSeenByB.length === 0, `tenantB rows=${bpSeenByB.length}`);

  // L3 NEG — DB belt foreign tenant (distinct PK to avoid conflict)
  let bpXt = false, bpXtErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      db.insert(biometricProfiles).values({ userId: BIO_UID_XT, tenantId: tenantB, sampleCount: 1, confidenceScore: "0.1" })
    );
  } catch (e: any) { bpXt = true; bpXtErr = String(e?.code ?? e?.message ?? e); }
  check("BP-L3 direct insert tenant_id=B under GUC=A rejected [RLS WITH CHECK NEG — DB belt]", bpXt && RLS_ERR.test(bpXtErr), `rejected=${bpXt} err=${bpXtErr}`);

  // L4 NEG — fail-closed guard
  let bpFc = false, bpFcMsg = "";
  try { await saveBiometricProfile({ userId: BIO_UID_XT, sampleCount: 1, confidenceScore: 0.1 } as any, ""); } catch (e: any) { bpFc = true; bpFcMsg = String(e?.message ?? e); }
  check("BP-L4 saveBiometricProfile without tenantId throws fail-closed guard [writer-binding NEG]", bpFc && /tenantId is required/i.test(bpFcMsg), `threw=${bpFc} msg=${bpFcMsg}`);

  // L5 NEG — DB belt null tenant
  let bpNull = false, bpNullErr = "";
  try {
    await runAsTenant(tenantA, async () =>
      db.insert(biometricProfiles).values({ userId: BIO_UID_NULL, tenantId: null as any, sampleCount: 1, confidenceScore: "0.1" })
    );
  } catch (e: any) { bpNull = true; bpNullErr = String(e?.code ?? e?.message ?? e); }
  check("BP-L5 direct NULL-tenant insert rejected by DB belt [NOT NULL + WITH CHECK NEG]", bpNull && NULL_ERR.test(bpNullErr), `rejected=${bpNull} err=${bpNullErr}`);

  // ── cleanup (as owner tenant A; RLS permits A to delete its own rows) ──────
  await runAsTenant(tenantA, async () => {
    await db.delete(webhookLogs).where(eq(webhookLogs.id, wlRow.id));
    await db.delete(webhookConfigs).where(eq(webhookConfigs.id, wcRow.id));
    await db.delete(webhookConfigs).where(eq(webhookConfigs.id, wcParent.id));
    await db.delete(threatFeeds).where(eq(threatFeeds.id, `${MARK}-tf`));
    await db.delete(threatIndicators).where(eq(threatIndicators.id, `${MARK}-ti`));
    await db.delete(threatFeedSyncLog).where(eq(threatFeedSyncLog.id, `${MARK}-tfsl`));
    await db.delete(biometricProfiles).where(eq(biometricProfiles.userId, BIO_UID_POS));
  });
  const leftWc = await runAsTenant(tenantA, async () => db.select().from(webhookConfigs).where(eq(webhookConfigs.id, wcRow.id)));
  const leftWl = await runAsTenant(tenantA, async () => db.select().from(webhookLogs).where(eq(webhookLogs.id, wlRow.id)));
  const leftTf = await runAsTenant(tenantA, async () => db.select().from(threatFeeds).where(eq(threatFeeds.id, `${MARK}-tf`)));
  const leftTi = await runAsTenant(tenantA, async () => db.select().from(threatIndicators).where(eq(threatIndicators.id, `${MARK}-ti`)));
  const leftTfsl = await runAsTenant(tenantA, async () => db.select().from(threatFeedSyncLog).where(eq(threatFeedSyncLog.id, `${MARK}-tfsl`)));
  const leftBp = await runAsTenant(tenantA, async () => db.select().from(biometricProfiles).where(eq(biometricProfiles.userId, BIO_UID_POS)));
  check(
    "ZZ cleanup removed all synthetic rows [hygiene]",
    leftWc.length === 0 && leftWl.length === 0 && leftTf.length === 0 && leftTi.length === 0 && leftTfsl.length === 0 && leftBp.length === 0,
    `wc=${leftWc.length} wl=${leftWl.length} tf=${leftTf.length} ti=${leftTi.length} tfsl=${leftTfsl.length} bp=${leftBp.length}`,
  );

  lines.push("");
  lines.push(`RESULT: ${pass} PASS / ${fail} FAIL  (total ${pass + fail})`);
  console.log(lines.join("\n"));

  await appPool.end().catch(() => {});
  await ddlPool.end().catch(() => {});
  process.exit(fail === 0 ? 0 : 1);
}

main().catch((e) => {
  console.error(lines.join("\n"));
  console.error("HARNESS ERROR:", e);
  process.exit(2);
});
