import { describe, test, expect, beforeEach } from "bun:test";

// Mock localStorage
const storage = new Map<string, string>();
const localStorageMock = {
  getItem: (key: string) => storage.get(key) ?? null,
  setItem: (key: string, value: string) => storage.set(key, value),
  removeItem: (key: string) => storage.delete(key),
  clear: () => storage.clear(),
  get length() {
    return storage.size;
  },
  key: (_index: number) => null,
};

Object.defineProperty(globalThis, "localStorage", {
  value: localStorageMock,
  writable: true,
});

// Import after mock is set up
const { getPeerId } = await import("../peer.js");

describe("getPeerId", () => {
  beforeEach(() => {
    storage.clear();
  });

  test("generates a UUID", () => {
    const id = getPeerId();
    expect(id).toMatch(
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
    );
  });

  test("persists and returns the same ID on subsequent calls", () => {
    const id1 = getPeerId();
    const id2 = getPeerId();
    expect(id1).toBe(id2);
  });

  test("stores the ID in localStorage", () => {
    const id = getPeerId();
    expect(storage.get("p2p-poll-peer-id")).toBe(id);
  });
});
