type StorageValueMap = Map<string, string>;

function createMemoryStorage(seed: StorageValueMap = new Map()): Storage {
  const store = seed;

  return {
    get length() {
      return store.size;
    },
    clear() {
      store.clear();
    },
    getItem(key: string) {
      return store.has(key) ? store.get(key)! : null;
    },
    key(index: number) {
      return Array.from(store.keys())[index] ?? null;
    },
    removeItem(key: string) {
      store.delete(key);
    },
    setItem(key: string, value: string) {
      store.set(key, String(value));
    },
  };
}

function ensureLocalStorageShape() {
  const candidate = globalThis.localStorage as Partial<Storage> | undefined;

  if (candidate && typeof candidate.getItem === "function") {
    return;
  }

  const seededEntries =
    candidate && typeof candidate === "object"
      ? Object.entries(candidate).filter(
          (entry): entry is [string, string] => typeof entry[1] === "string",
        )
      : [];

  Object.defineProperty(globalThis, "localStorage", {
    configurable: true,
    enumerable: true,
    writable: true,
    value: createMemoryStorage(new Map(seededEntries)),
  });
}

export async function register() {
  ensureLocalStorageShape();
}
