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

test("composer drafts persist per session and clear after submission", async () => {
  const draftState = await import("./composer-draft.js").catch(() => ({}));
  assert.equal(typeof draftState.loadComposerDraft, "function");
  assert.equal(typeof draftState.saveComposerDraft, "function");
  assert.equal(typeof draftState.clearComposerDraft, "function");

  const values = new Map();
  const storage = {
    getItem: (key) => values.get(key) ?? null,
    setItem: (key, value) => values.set(key, value),
    removeItem: (key) => values.delete(key)
  };

  draftState.saveComposerDraft(storage, "session-a", "steer this turn");

  assert.equal(draftState.loadComposerDraft(storage, "session-a"), "steer this turn");
  assert.equal(draftState.loadComposerDraft(storage, "session-b"), "");

  draftState.clearComposerDraft(storage, "session-a");
  assert.equal(draftState.loadComposerDraft(storage, "session-a"), "");
});

test("conversation stores drafts in durable local storage", async () => {
  const source = await import("node:fs/promises").then(({ readFile }) => readFile(new URL("./useConversation.js", import.meta.url), "utf8"));

  assert.doesNotMatch(source, /globalThis\.sessionStorage/);
  assert.match(source, /globalThis\.localStorage/);
});

test("composer draft commits debounce typing and flush the latest value", async () => {
  const draftState = await import("./composer-draft.js");
  assert.equal(typeof draftState.createComposerDraftCommitter, "function");

  const commits = [];
  const cleared = [];
  const timers = [];
  const committer = draftState.createComposerDraftCommitter((value) => commits.push(value), {
    setTimer(callback, delay) {
      const timer = { callback, delay };
      timers.push(timer);
      return timer;
    },
    clearTimer(timer) {
      cleared.push(timer);
    }
  });

  committer.schedule("ㅎ");
  committer.schedule("한글");

  assert.deepEqual(commits, []);
  assert.equal(timers.at(-1).delay, 300);
  assert.deepEqual(cleared, [timers[0]]);

  timers.at(-1).callback();
  assert.deepEqual(commits, ["한글"]);

  committer.schedule("마지막 초안");
  committer.flush();
  assert.deepEqual(commits, ["한글", "마지막 초안"]);
  assert.equal(cleared.at(-1), timers.at(-1));
});
