import { describe, it, expect, beforeEach } from "vitest";
import {
  getOrCreateIdempotencyKey,
  resetIdempotencyKey,
  idempotencyStorageKey,
} from "../idempotency";

describe("getOrCreateIdempotencyKey", () => {
  beforeEach(() => {
    localStorage.clear();
  });

  it("returns a stable UUID across calls for the same token", () => {
    const a = getOrCreateIdempotencyKey("tok1");
    const b = getOrCreateIdempotencyKey("tok1");
    expect(a).toBe(b);
    expect(a).toMatch(
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
    );
  });

  it("persists the key in localStorage keyed by token", () => {
    const key = getOrCreateIdempotencyKey("tok1");
    expect(localStorage.getItem(idempotencyStorageKey("tok1"))).toBe(key);
  });

  it("uses independent keys for different tokens", () => {
    const a = getOrCreateIdempotencyKey("tok1");
    const b = getOrCreateIdempotencyKey("tok2");
    expect(a).not.toBe(b);
  });

  it("reuses an existing persisted key (safe replay across reloads)", () => {
    localStorage.setItem(idempotencyStorageKey("tok1"), "preexisting-key");
    expect(getOrCreateIdempotencyKey("tok1")).toBe("preexisting-key");
  });

  it("regenerates a fresh key only after reset (post-submit)", () => {
    const first = getOrCreateIdempotencyKey("tok1");
    resetIdempotencyKey("tok1");
    expect(localStorage.getItem(idempotencyStorageKey("tok1"))).toBeNull();
    const second = getOrCreateIdempotencyKey("tok1");
    expect(second).not.toBe(first);
  });
});
