import test from "node:test";
import assert from "node:assert/strict";
import { clearNewChatDraft, loadNewChatDraft, saveNewChatDraft } from "./new-chat-draft.js";

test("new chat picker draft survives remounts", () => {
  const storage = memoryStorage();
  const draft = { search: "remote", newProject: true, name: "codex-mobile" };

  saveNewChatDraft(storage, draft);

  assert.deepEqual(loadNewChatDraft(storage), draft);
});

test("new chat picker draft tolerates invalid storage and clears after success", () => {
  const storage = memoryStorage();
  storage.setItem("codexRemote.newChatDraft", "not-json");

  assert.deepEqual(loadNewChatDraft(storage), { search: "", newProject: false, name: "" });

  saveNewChatDraft(storage, { search: "a", newProject: false, name: "" });
  clearNewChatDraft(storage);
  assert.deepEqual(loadNewChatDraft(storage), { search: "", newProject: false, name: "" });
});

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