import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
import { test } from "bun:test";

import { subscribeWorkbenchProjectionCommits, WORKBENCH_PROJECTION_CHANNEL } from "./runtime-store-postgres-notify.ts";

test("Postgres LISTEN fans committed projection scope out and releases its dedicated connection", async () => {
  const queries = [];
  let released = 0;
  const client = new EventEmitter();
  client.query = async (sql) => { queries.push(sql); return { rows: [] }; };
  client.release = () => { released += 1; };
  const pool = { async connect() { return client; } };
  const store = { async getQueryClient() { return pool; }, logger: null };
  const signals = [];

  const unsubscribe = await subscribeWorkbenchProjectionCommits(store, (signal) => signals.push(signal));
  assert.deepEqual(queries, [`LISTEN ${WORKBENCH_PROJECTION_CHANNEL}`]);

  client.emit("notification", { channel: WORKBENCH_PROJECTION_CHANNEL, payload: JSON.stringify({ sessionId: "ses_notify", traceId: "trc_notify", outboxSeq: 12 }) });
  assert.deepEqual(signals, [{ sessionId: "ses_notify", traceId: "trc_notify", outboxSeq: 12, valuesRedacted: true }]);

  await unsubscribe();
  assert.equal(queries.at(-1), `UNLISTEN ${WORKBENCH_PROJECTION_CHANNEL}`);
  assert.equal(released, 1);
});
