import { describe, expect, it, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import { type ReactElement } from "react";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import { AuthProvider } from "../AuthProvider";
import { SESSION_EXPIRED_EVENT } from "../../api/client";

function CurrentLocation(): ReactElement {
  const location = useLocation();
  return <div data-testid="location">{location.pathname}</div>;
}

describe("AuthProvider", () => {
  beforeEach(() => {
    sessionStorage.clear();
    vi.restoreAllMocks();
  });

  it("clears auth state and redirects to /login when session-expired fires", async () => {
    sessionStorage.setItem("bangui_token", "token");
    sessionStorage.setItem("bangui_expires_at", new Date(Date.now() + 10000).toISOString());

    render(
      <FluentProvider theme={webLightTheme}>
        <MemoryRouter initialEntries={["/private"]}>
          <AuthProvider>
            <Routes>
              <Route path="*" element={<CurrentLocation />} />
            </Routes>
          </AuthProvider>
        </MemoryRouter>
      </FluentProvider>,
    );

    window.dispatchEvent(new Event(SESSION_EXPIRED_EVENT));

    await waitFor(() => {
      expect(screen.getByTestId("location")).toHaveTextContent("/login");
    });
    expect(sessionStorage.getItem("bangui_token")).toBeNull();
    expect(sessionStorage.getItem("bangui_expires_at")).toBeNull();
  });
});
