import { expect, test } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import type { ReactNode } from "react";

import { server } from "../test/server";
import { useSetVisibility } from "./queries";
import { keys } from "./query-keys";

test("changing an object's visibility invalidates the active search query", async () => {
  server.use(
    http.post("/api/admin/objects/:id/visibility", () => new HttpResponse(null, { status: 204 })),
  );
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  qc.setQueryData(keys.searchResults("amphora", null), { pages: [], pageParams: [] });

  const wrapper = ({ children }: { children: ReactNode }) => (
    <QueryClientProvider client={qc}>{children}</QueryClientProvider>
  );
  const { result } = renderHook(() => useSetVisibility(), { wrapper });

  await result.current.mutateAsync({ id: "o1", visibility: "public" });

  await waitFor(() =>
    expect(qc.getQueryState(keys.searchResults("amphora", null))?.isInvalidated).toBe(true),
  );
});
