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

const authState = {
  activeNavigator: undefined,
  error: undefined as Error | undefined,
  isAuthenticated: false,
  isLoading: false,
  removeUser: vi.fn(async () => undefined),
};

vi.mock("react-oidc-context", () => ({
  useAuth: () => authState,
}));

function renderAuthGuard(initialEntry = "/users") {
  return render(
    <MemoryRouter initialEntries={[initialEntry]}>
      <Routes>
        <Route path="/" element={<AuthGuard />}>
          <Route path="users" element={<div>Users outlet</div>} />
        </Route>
        <Route path="/login" element={<div>Login outlet</div>} />
      </Routes>
    </MemoryRouter>,
  );
}

describe("AuthGuard", () => {
  beforeEach(() => {
    (
      window as Window & typeof globalThis & { _IS_TEST_MODE?: boolean }
    )._IS_TEST_MODE = false;
    authState.activeNavigator = undefined;
    authState.error = undefined;
    authState.isAuthenticated = false;
    authState.isLoading = false;
    authState.removeUser.mockClear();
    window.localStorage.clear();
  });

  it("clears stale auth state and returns to login when OIDC reports an error", async () => {
    window.localStorage.setItem("admin_session", "stale-token");
    authState.error = new Error("stale session");

    renderAuthGuard();

    await waitFor(() => {
      expect(authState.removeUser).toHaveBeenCalled();
    });
    await screen.findByText("Login outlet");
    expect(window.localStorage.getItem("admin_session")).toBeNull();
  });
});
