import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
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 { ContentPage } from "./ContentPage";
import * as contentApi from "@modules/content/api/contentApi";

function renderPage(slug = "about") {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false } }
  });
  return render(
    <QueryClientProvider client={queryClient}>
      <MemoryRouter initialEntries={[`/pages/${slug}`]}>
        <Routes>
          <Route path="/pages/:slug" element={<ContentPage />} />
        </Routes>
      </MemoryRouter>
    </QueryClientProvider>
  );
}

describe("ContentPage", () => {
  beforeEach(() => {
    vi.restoreAllMocks();
  });

  it("renders fetched page title and body", async () => {
    vi.spyOn(contentApi, "getPageBySlug").mockResolvedValue({
      id: "1",
      slug: "about",
      title: "About Us",
      body: "<p>About content</p>",
      status: "published"
    });

    renderPage("about");

    await waitFor(() => {
      expect(screen.getByRole("heading", { name: "About Us" })).toBeInTheDocument();
    });
    expect(screen.getByText("About content")).toBeInTheDocument();
  });
});
