import test from "node:test";
import assert from "node:assert/strict";
import { readSavedContext, readSavedSession, readSavedView, writeSavedContext, writeSavedSession, writeSavedView } from "./app-persistence.js";

test("reads saved session id from storage", () => {
  const storage = memoryStorage();
  storage.setItem("codexRemote.currentSession", JSON.stringify({ sessionId: "s" }));

  assert.deepEqual(readSavedSession(storage), { sessionId: "s" });
});

test("ignores invalid saved session data", () => {
  const storage = memoryStorage();
  storage.setItem("codexRemote.currentSession", JSON.stringify({ sessionId: "" }));

  assert.equal(readSavedSession(storage), null);
});

test("writes opened session id to storage", () => {
  const storage = memoryStorage();

  writeSavedSession(storage, { id: "s" });

  assert.deepEqual(JSON.parse(storage.getItem("codexRemote.currentSession")), { sessionId: "s" });
});

test("reads saved account and workspace from storage", () => {
  const storage = memoryStorage();
  storage.setItem("codexRemote.currentContext", JSON.stringify({ accountId: "b", workspaceId: "w" }));

  assert.deepEqual(readSavedContext(storage), { accountId: "b", workspaceId: "w" });
});

test("writes selected account and workspace to storage", () => {
  const storage = memoryStorage();

  writeSavedContext(storage, { accountId: "b", workspaceId: "w" });

  assert.deepEqual(JSON.parse(storage.getItem("codexRemote.currentContext")), { accountId: "b", workspaceId: "w" });
});

test("reads and writes the last visible app screen", () => {
  const storage = memoryStorage();

  writeSavedView(storage, "settings");

  assert.equal(readSavedView(storage), "settings");
});

test("ignores unsupported saved app screens", () => {
  const storage = memoryStorage();
  storage.setItem("codexRemote.currentView", "accounts");

  assert.equal(readSavedView(storage), "threads");
});

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)
  };
}
