/**
 * VF-S5 disambiguation probe (throwaway).
 * Isolates the one link no leg tests: a SUCCESSFUL persist that COMMITS, then
 * read back via the independent owner pool. If readback === 1 the persist +
 * commit + owner-visibility chain works in-process and leg-1's failure is
 * specific to the real server route; if readback === 0 the readback/visibility
 * itself is broken.
 */
import pg from "pg";
import { sql } from "drizzle-orm";
import { db, appPool, ddlPool, tenantContext, type DrizzleDb } from "../server/db";
import {
  analyzeTransaction,
  persistKytResultDurable,
  type TransactionContext,
} from "../server/lib/kyt-engine";

const owner = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const base = Date.now() * 100;
const TENANT = "aegis-sovereign";

async function withRequestTx<T>(tenantId: string, fn: () => Promise<T>): Promise<T> {
  return await db.transaction(async (tx) => {
    await tx.execute(sql`SELECT set_config('app.current_tenant_id', ${tenantId}, true)`);
    return await tenantContext.run({ runner: tx as unknown as DrizzleDb, tenantId }, fn);
  });
}

function ctx(userId: number): TransactionContext {
  return {
    userId,
    amount: 250_000,
    currency: "UGX",
    recipientId: "vf-s5-probe",
    recipientType: "KNOWN",
    channel: "WEB",
    timeOfDay: 12,
    isRecurring: false,
  };
}

async function main() {
  const uidNum = base + 1;
  const uidStr = String(uidNum);

  // owner-side DB identity (host/db) for cross-check vs appPool
  const ownerId = await owner.query(
    "SELECT current_database() AS db, current_user AS usr, inet_server_addr()::text AS host, inet_server_port() AS port",
  );
  const appId = await appPool.query(
    "SELECT current_database() AS db, current_user AS usr, inet_server_addr()::text AS host, inet_server_port() AS port",
  );
  console.log("owner  identity:", JSON.stringify(ownerId.rows[0]));
  console.log("appPool identity:", JSON.stringify(appId.rows[0]));

  // POSITIVE: persist inside a committing request-tx (no rollback path).
  const result = analyzeTransaction(ctx(uidNum));
  const persisted = await withRequestTx(TENANT, () =>
    persistKytResultDurable(result, ctx(uidNum), TENANT),
  );
  console.log(`persisted=${persisted} (expected true)`);

  // small settle then read back via INDEPENDENT owner pool
  await new Promise((r) => setTimeout(r, 800));
  const ownerRb = await owner.query<{ tenant_id: string | null }>(
    "SELECT tenant_id FROM kyt_results WHERE user_id = $1",
    [uidStr],
  );
  console.log(`owner readback rows=${ownerRb.rowCount} tenant_ids=${JSON.stringify(ownerRb.rows.map((r) => r.tenant_id))}`);

  // cross-check: read back via ddlPool (superuser, BYPASSRLS) too
  const ddlRb = await ddlPool.query<{ tenant_id: string | null }>(
    "SELECT tenant_id FROM kyt_results WHERE user_id = $1",
    [uidStr],
  );
  console.log(`ddlPool readback rows=${ddlRb.rowCount} tenant_ids=${JSON.stringify(ddlRb.rows.map((r) => r.tenant_id))}`);

  // cleanup
  const del = await owner.query("DELETE FROM kyt_results WHERE user_id = $1", [uidStr]);
  console.log(`cleanup deleted ${del.rowCount} row(s).`);

  await owner.end();
  await appPool.end();
  await ddlPool.end();
  process.exit(0);
}

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