import { jest } from "@jest/globals";

// Set environment variables before importing
process.env.REACT_APP_MSAL_CLIENT_ID = "test-client-id";
process.env.REACT_APP_MSAL_TENANT_ID = "test-tenant-id";
process.env.REACT_APP_MSAL_REDIRECT_URI = "http://localhost:3000";

describe("authConfig", () => {
  beforeEach(() => {
    jest.resetModules();
  });

  it("should export msalConfig with correct values", async () => {
    const { msalConfig } = await import("../authConfig.js");

    expect(msalConfig).toBeDefined();
    expect(msalConfig.auth).toBeDefined();
    expect(msalConfig.auth.clientId).toBe("test-client-id");
    expect(msalConfig.auth.authority).toContain("test-tenant-id");
    expect(msalConfig.auth.redirectUri).toBe("http://localhost:3000");
  });

  it("should export loginRequest with User.Read scope", async () => {
    const { loginRequest } = await import("../authConfig.js");

    expect(loginRequest).toBeDefined();
    expect(loginRequest.scopes).toContain("User.Read");
  });

  it("should export graphConfig with correct endpoint", async () => {
    const { graphConfig } = await import("../authConfig.js");

    expect(graphConfig).toBeDefined();
    expect(graphConfig.graphMeEndpoint).toBe("https://graph.microsoft.com/v1.0/me");
  });

  it("should have correct cache configuration", async () => {
    const { msalConfig } = await import("../authConfig.js");

    expect(msalConfig.cache).toBeDefined();
    expect(msalConfig.cache.cacheLocation).toBe("localStorage");
    expect(msalConfig.cache.storeAuthStateInCookie).toBe(false);
  });

  it("should handle missing environment variables gracefully", async () => {
    // Reset modules and clear env vars
    jest.resetModules();
    const originalClientId = process.env.REACT_APP_MSAL_CLIENT_ID;
    const originalTenantId = process.env.REACT_APP_MSAL_TENANT_ID;
    const originalRedirectUri = process.env.REACT_APP_MSAL_REDIRECT_URI;

    delete process.env.REACT_APP_MSAL_CLIENT_ID;
    delete process.env.REACT_APP_MSAL_TENANT_ID;
    delete process.env.REACT_APP_MSAL_REDIRECT_URI;

    // Spy on console.warn
    const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});

    const { msalConfig } = await import("../authConfig.js");

    expect(msalConfig.auth.clientId).toBe("");
    expect(msalConfig.auth.authority).toContain("common");
    expect(msalConfig.auth.redirectUri).toBe("http://localhost:3000");

    warnSpy.mockRestore();

    // Restore env vars
    process.env.REACT_APP_MSAL_CLIENT_ID = originalClientId;
    process.env.REACT_APP_MSAL_TENANT_ID = originalTenantId;
    process.env.REACT_APP_MSAL_REDIRECT_URI = originalRedirectUri;
  });
});
