import { describe, expect, test, vi } from "vitest";

import { createSessionTokenResolver } from "./session-token-resolver";

describe("createSessionTokenResolver", () => {
  test("logout clears the cached JWT before another session resolves", async () => {
    const resolveToken = createSessionTokenResolver();
    const loadFirstToken = vi.fn(() => Promise.resolve("jwt-for-user-a"));

    await expect(resolveToken("session-a", loadFirstToken)).resolves.toBe(
      "jwt-for-user-a"
    );
    await expect(
      resolveToken("session-a", () => Promise.resolve("unexpected-token"))
    ).resolves.toBe("jwt-for-user-a");
    expect(loadFirstToken).toHaveBeenCalledTimes(1);

    const loadWhileLoggedOut = vi.fn(() => Promise.resolve("stale-jwt"));
    await expect(resolveToken(null, loadWhileLoggedOut)).resolves.toBeNull();
    expect(loadWhileLoggedOut).not.toHaveBeenCalled();

    const loadSecondToken = vi.fn(() => Promise.resolve("jwt-for-user-b"));
    await expect(resolveToken("session-b", loadSecondToken)).resolves.toBe(
      "jwt-for-user-b"
    );
    expect(loadSecondToken).toHaveBeenCalledTimes(1);
  });

  test("a direct user switch never returns the previous session token", async () => {
    const resolveToken = createSessionTokenResolver();

    await expect(
      resolveToken("session-a", () => Promise.resolve("jwt-for-user-a"))
    ).resolves.toBe("jwt-for-user-a");
    await expect(
      resolveToken("session-b", () => Promise.resolve("jwt-for-user-b"))
    ).resolves.toBe("jwt-for-user-b");
  });
});
