import { describe, expect, it } from "vitest";
import {
  DEFAULT_OIDC_REDIRECT_PATH,
  DEFAULT_OIDC_SCOPE,
  buildCommonOidcRuntimeConfig,
  buildCommonUserManagerSettings,
  shouldStartLoginRedirect,
} from "../../../../common/core/auth";

describe("common auth helpers", () => {
  it("builds the runtime OIDC config with sensible defaults", () => {
    const config = buildCommonOidcRuntimeConfig({
      authority: "https://issuer.example.com",
      clientId: "client-1",
      userStore: { kind: "store" },
    });

    expect(config).toEqual({
      authority: "https://issuer.example.com",
      client_id: "client-1",
      redirect_uri: `${window.location.origin}${DEFAULT_OIDC_REDIRECT_PATH}`,
      response_type: "code",
      scope: DEFAULT_OIDC_SCOPE,
      post_logout_redirect_uri: window.location.origin,
      popup_redirect_uri: `${window.location.origin}${DEFAULT_OIDC_REDIRECT_PATH}`,
      userStore: { kind: "store" },
      automaticSilentRenew: false,
    });
  });

  it("copies user manager config and fills missing string fields", () => {
    expect(
      buildCommonUserManagerSettings({
        authority: "https://issuer.example.com",
      }),
    ).toEqual({
      authority: "https://issuer.example.com",
      client_id: "",
      redirect_uri: "",
    });
  });

  it("decides when to start login redirects", () => {
    expect(
      shouldStartLoginRedirect({
        pathname: "/clients",
        isRedirecting: false,
      }),
    ).toBe(true);

    expect(
      shouldStartLoginRedirect({
        pathname: "/login",
        isRedirecting: false,
      }),
    ).toBe(false);

    expect(
      shouldStartLoginRedirect({
        pathname: `${DEFAULT_OIDC_REDIRECT_PATH}/callback`,
        isRedirecting: false,
      }),
    ).toBe(false);

    expect(
      shouldStartLoginRedirect({
        pathname: "/clients",
        isRedirecting: true,
      }),
    ).toBe(false);
  });
});
