import { cleanup, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { AdminGuard } from "@app/router/guards/AdminGuard";
import { useAuthStore } from "@modules/auth/store/authStore";

function TestChild(): JSX.Element {
  return <h1>Admin area</h1>;
}

describe("AdminGuard", () => {
  beforeEach(() => {
    useAuthStore.getState().clearSession();
    useAuthStore.getState().setBootstrapped(true);
  });

  afterEach(() => {
    cleanup();
  });

  it("redirects guests to login", () => {
    render(
      <MemoryRouter initialEntries={["/admin"]}>
        <AdminGuard>
          <TestChild />
        </AdminGuard>
      </MemoryRouter>
    );
    expect(screen.queryByRole("heading", { name: "Admin area" })).not.toBeInTheDocument();
  });

  it("renders admin content for admin users", () => {
    useAuthStore.getState().setSession("token", {
      id: "1",
      email: "admin@compton.example",
      role: "admin",
      is_superuser: false,
      status: "active"
    });

    render(
      <MemoryRouter initialEntries={["/admin"]}>
        <AdminGuard>
          <TestChild />
        </AdminGuard>
      </MemoryRouter>
    );

    expect(screen.getAllByRole("heading", { name: "Admin area" })).toHaveLength(1);
  });
});
