import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter, Routes, Route } from "react-router-dom";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import { SetupGuard } from "../SetupGuard";

// Mock the setup API module so tests never hit a real network.
vi.mock("../../api/setup", () => ({
  getSetupStatus: vi.fn(),
}));

import { getSetupStatus } from "../../api/setup";

const mockedGetSetupStatus = vi.mocked(getSetupStatus);

function renderGuard() {
  return render(
    <FluentProvider theme={webLightTheme}>
      <MemoryRouter initialEntries={["/dashboard"]}>
        <Routes>
          <Route
            path="/dashboard"
            element={
              <SetupGuard>
                <div data-testid="protected-content">Protected</div>
              </SetupGuard>
            }
          />
          <Route
            path="/setup"
            element={<div data-testid="setup-page">Setup Page</div>}
          />
        </Routes>
      </MemoryRouter>
    </FluentProvider>,
  );
}

describe("SetupGuard", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("shows a spinner while the setup status is loading", () => {
    // getSetupStatus resolves eventually — spinner should show immediately.
    mockedGetSetupStatus.mockReturnValue(new Promise(() => {}));
    renderGuard();
    expect(screen.getByRole("progressbar")).toBeInTheDocument();
  });

  it("renders children when setup is complete", async () => {
    mockedGetSetupStatus.mockResolvedValue({ completed: true });
    renderGuard();
    await waitFor(() => {
      expect(screen.getByTestId("protected-content")).toBeInTheDocument();
    });
  });

  it("redirects to /setup when setup is not complete", async () => {
    mockedGetSetupStatus.mockResolvedValue({ completed: false });
    renderGuard();
    await waitFor(() => {
      expect(screen.getByTestId("setup-page")).toBeInTheDocument();
    });
    expect(screen.queryByTestId("protected-content")).not.toBeInTheDocument();
  });

  it("renders an error card when the setup status check fails", async () => {
    mockedGetSetupStatus.mockRejectedValue(new Error("Network error"));
    renderGuard();

    await waitFor(() => {
      expect(screen.getByRole("button", { name: /retry/i })).toBeInTheDocument();
    });
    expect(screen.getByText(/network error/i)).toBeInTheDocument();
    expect(screen.queryByTestId("protected-content")).not.toBeInTheDocument();
    expect(screen.queryByTestId("setup-page")).not.toBeInTheDocument();
  });

  it("retries setup status fetch when Retry is clicked", async () => {
    mockedGetSetupStatus.mockRejectedValueOnce(new Error("Network error"));
    mockedGetSetupStatus.mockResolvedValueOnce({ completed: true });

    renderGuard();

    await waitFor(() => {
      expect(screen.getByRole("button", { name: /retry/i })).toBeInTheDocument();
    });

    fireEvent.click(screen.getByRole("button", { name: /retry/i }));

    await waitFor(() => {
      expect(screen.getByTestId("protected-content")).toBeInTheDocument();
    });
  });
});
