import assert from "node:assert/strict";
import { describe, it } from "node:test";

import {
  TABLE_VIEW_MODE_DEFAULT_VERSION_KEY,
  TABLE_VIEW_MODE_STORAGE_KEY,
  readStoredTableMode
} from "./tableViewMode.js";

function createStorage(initialValues = {}) {
  const values = new Map(Object.entries(initialValues));
  return {
    getItem(key) {
      return values.has(key) ? values.get(key) : null;
    },
    setItem(key, value) {
      values.set(key, String(value));
    }
  };
}

describe("readStoredTableMode", () => {
  it("migrates existing overview preference to wide for the new default", () => {
    const storage = createStorage({
      [TABLE_VIEW_MODE_STORAGE_KEY]: "overview"
    });

    assert.equal(readStoredTableMode(storage), "wide");
    assert.equal(storage.getItem(TABLE_VIEW_MODE_STORAGE_KEY), "wide");
    assert.equal(storage.getItem(TABLE_VIEW_MODE_DEFAULT_VERSION_KEY), "wide-v1");
  });

  it("keeps a user-selected overview after the wide default migration has already run", () => {
    const storage = createStorage({
      [TABLE_VIEW_MODE_STORAGE_KEY]: "overview",
      [TABLE_VIEW_MODE_DEFAULT_VERSION_KEY]: "wide-v1"
    });

    assert.equal(readStoredTableMode(storage), "overview");
  });

  it("defaults to wide when no preference exists", () => {
    const storage = createStorage({
      [TABLE_VIEW_MODE_DEFAULT_VERSION_KEY]: "wide-v1"
    });

    assert.equal(readStoredTableMode(storage), "wide");
  });
});
