/**
 * Run with: node --experimental-strip-types --test src/lib/storage-keys.test.ts
 */
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { migrateStorageKeys, STORAGE_KEYS } from "./storage-keys.ts";

function memStorage(init: Record<string, string>) {
  const m = new Map(Object.entries(init));
  return {
    map: m,
    getItem: (k: string) => (m.has(k) ? (m.get(k) as string) : null),
    setItem: (k: string, v: string) => void m.set(k, v),
    removeItem: (k: string) => void m.delete(k),
  };
}

describe("storage key migration", () => {
  it("moves old goal-figther-* data to the new goal-fighters-* keys", () => {
    const s = memStorage({ "goal-figther-save-v1": '{"wins":7}', "goal-figther-mute": "1" });
    migrateStorageKeys(s);
    assert.equal(s.getItem(STORAGE_KEYS.save), '{"wins":7}');
    assert.equal(s.getItem(STORAGE_KEYS.mute), "1");
    assert.equal(s.getItem("goal-figther-save-v1"), null);
    assert.equal(s.getItem("goal-figther-mute"), null);
  });

  it("never overwrites data already saved under the new keys", () => {
    const s = memStorage({ "goal-figther-save-v1": '{"wins":1}', [STORAGE_KEYS.save]: '{"wins":9}' });
    migrateStorageKeys(s);
    assert.equal(s.getItem(STORAGE_KEYS.save), '{"wins":9}');
    assert.equal(s.getItem("goal-figther-save-v1"), null);
  });

  it("keys use the corrected game name", () => {
    for (const k of Object.values(STORAGE_KEYS)) assert.match(k, /^goal-fighters-/);
  });
});
