import test from "node:test";
import assert from "node:assert/strict";

test("persistSessionByKey serializes writes for the same page key", async () => {
  const calls = [];
  let activeWrites = 0;
  let maxActiveWrites = 0;
  let lastStored = null;

  globalThis.chrome = {
    storage: {
      local: {
        async set(payload) {
          activeWrites += 1;
          maxActiveWrites = Math.max(maxActiveWrites, activeWrites);
          const text = payload["page-1"]?.chatSession?.messages?.[0]?.text || "";
          calls.push(text);
          await new Promise((resolve) => setTimeout(resolve, text === "first" ? 30 : 0));
          lastStored = text;
          activeWrites -= 1;
        }
      }
    }
  };

  const { persistSessionByKey } = await import(`../sidepanel/services/session-storage.js?test=${Date.now()}`);

  const first = persistSessionByKey(
    "page-1",
    { messages: [{ role: "assistant", text: "first" }], attachmentCache: {} },
    null
  );
  const second = persistSessionByKey(
    "page-1",
    { messages: [{ role: "assistant", text: "second" }], attachmentCache: {} },
    null
  );

  await Promise.all([first, second]);

  assert.deepEqual(calls, ["first", "second"]);
  assert.equal(maxActiveWrites, 1);
  assert.equal(lastStored, "second");
});
