import { render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import HealthStatusModal from "./HealthStatusModal";
import { apiGetJson } from "../api/client";

vi.mock("../api/client", () => ({
  apiGetJson: vi.fn(),
}));

describe("HealthStatusModal", () => {
  it("shows authentication diagnostics from /api/health", async () => {
    const mockedApiGetJson = vi.mocked(apiGetJson);
    mockedApiGetJson.mockImplementation(async (url: string) => {
      if (url.startsWith("/api/health")) {
        return {
          ok: false,
          summary: { required_ok: 2, required_total: 3, total_checks: 3 },
          checks: [],
          env: {},
          auth: {
            required: true,
            enabled: false,
            issuer: "https://tenant.us.auth0.com/",
            audience: "",
            email_claim: "https://masterstelecom.com/email",
            allowed_domains: ["masterstelecom.com", "verizon.com"],
            config_error: "AUTH_REQUIRED is enabled but Auth0 config is invalid.",
            config_details: ["Missing required auth setting: AUTH0_DOMAIN."],
            config_warnings: ["AUTH0_JWKS_TTL_SECONDS is invalid ('x'); defaulting to 600 seconds."],
          },
        };
      }
      throw new Error("metrics unavailable");
    });

    render(<HealthStatusModal open onClose={() => {}} />);

    await waitFor(() => {
      expect(screen.getByText("Authentication")).toBeInTheDocument();
    });

    expect(screen.getByText("Auth required")).toBeInTheDocument();
    expect(screen.getByText("Auth not enabled")).toBeInTheDocument();
    expect(screen.getByText("Config details")).toBeInTheDocument();
    expect(screen.getByText("Config warnings")).toBeInTheDocument();
    expect(screen.getByText(/Missing required auth setting: AUTH0_DOMAIN/i)).toBeInTheDocument();
  });
});
