import { render, screen } from "@testing-library/react";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { MemoryRouter } from "react-router-dom";
import App from "@/app/App.jsx";
import { AppProviders } from "@/app/providers.jsx";
import { adminRoutes } from "@/app/router/routeConfig";

beforeEach(() => {
  window.localStorage.clear();
  vi.stubGlobal(
    "fetch",
    vi.fn(async () => new Response(JSON.stringify({ code: 401, message: "unauthorized" }), { status: 401 }))
  );
});

afterEach(() => {
  vi.unstubAllGlobals();
});

test("renders login route", async () => {
  renderWithRoute("/login");

  expect(await screen.findByText("HYApp 管理平台")).toBeInTheDocument();
});

test("redirects protected route to login when unauthenticated", async () => {
  renderWithRoute("/system/users");

  expect(await screen.findByText("HYApp 管理平台")).toBeInTheDocument();
});

test("admin routes declare menu code and permission", () => {
  expect(adminRoutes.length).toBeGreaterThan(0);
  expect(adminRoutes.every((route) => route.menuCode && route.permission)).toBe(true);
});

function renderWithRoute(route) {
  return render(
    <AppProviders>
      <MemoryRouter initialEntries={[route]}>
        <App />
      </MemoryRouter>
    </AppProviders>
  );
}
