import test from "node:test";
import assert from "node:assert/strict";
import { createRequestLock } from "./conversation-submit.js";

test("request lock ignores duplicate calls until the first settles", async () => {
  const lock = createRequestLock();
  let resolve;
  let calls = 0;
  const operation = () => {
    calls += 1;
    return new Promise((done) => { resolve = done; });
  };

  const first = lock.run(operation);
  const duplicate = lock.run(operation);

  assert.equal(calls, 1);
  assert.equal(duplicate, undefined);
  assert.equal(lock.pending(), true);
  resolve("ok");
  assert.equal(await first, "ok");
  assert.equal(lock.pending(), false);
});

test("request lock releases after failure so the operation can retry", async () => {
  const lock = createRequestLock();
  let calls = 0;
  await assert.rejects(lock.run(async () => { calls += 1; throw new Error("failed"); }), /failed/);
  await lock.run(async () => { calls += 1; });
  assert.equal(calls, 2);
});
