import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { findPersistedOidcUser } from "./oidcStorage";

class MemoryStorage implements Storage {
  private data = new Map<string, string>();

  get length() {
    return this.data.size;
  }

  clear(): void {
    this.data.clear();
  }

  getItem(key: string): string | null {
    return this.data.get(key) ?? null;
  }

  key(index: number): string | null {
    return Array.from(this.data.keys())[index] ?? null;
  }

  removeItem(key: string): void {
    this.data.delete(key);
  }

  setItem(key: string, value: string): void {
    this.data.set(key, value);
  }
}

describe("findPersistedOidcUser", () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date("2026-06-01T00:00:00.000Z"));
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it("returns the first valid, unexpired devfront user entry", () => {
    const storage = new MemoryStorage();
    storage.setItem("oidc.user:issuer:other-client", JSON.stringify({}));
    const expiresAt = Math.floor(Date.now() / 1000) + 3600;
    storage.setItem(
      "oidc.user:issuer:devfront",
      JSON.stringify({
        access_token: "token-1",
        expires_at: expiresAt,
        profile: { name: "Dev Admin" },
      }),
    );

    expect(findPersistedOidcUser(storage)).toEqual({
      access_token: "token-1",
      expires_at: expiresAt,
      profile: { name: "Dev Admin" },
    });
  });

  it("skips malformed, empty, and expired entries", () => {
    const storage = new MemoryStorage();
    storage.setItem("random", "value");
    storage.setItem("oidc.user:issuer:devfront", "not-json");
    storage.setItem(
      "oidc.user:issuer:devfront",
      JSON.stringify({
        access_token: "expired",
        expires_at: Math.floor(Date.now() / 1000) - 1,
      }),
    );

    expect(findPersistedOidcUser(storage)).toBeNull();
  });
});
