import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";

installStoragePolyfill("localStorage");
installStoragePolyfill("sessionStorage");

afterEach(() => {
    cleanup();
});

function installStoragePolyfill(name) {
    let storage;
    try {
        storage = window[name];
    } catch {
        storage = null;
    }

    if (storage?.getItem && storage?.setItem && storage?.removeItem && storage?.clear) {
        return;
    }

    const store = new Map();
    Object.defineProperty(window, name, {
        configurable: true,
        value: {
            clear() {
                store.clear();
            },
            getItem(key) {
                const normalizedKey = String(key);
                return store.has(normalizedKey) ? store.get(normalizedKey) : null;
            },
            key(index) {
                return Array.from(store.keys())[index] ?? null;
            },
            get length() {
                return store.size;
            },
            removeItem(key) {
                store.delete(String(key));
            },
            setItem(key, value) {
                store.set(String(key), String(value));
            },
        },
    });
}
