import { QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import { createAdminQueryClient } from "@/shared/query/client";
import { useAdminQuery } from "./useAdminQuery.js";

test("reuses cached query data by query key", async () => {
  const queryClient = createAdminQueryClient();
  const fetcher = vi.fn(async () => ({ value: 1 }));
  const wrapper = ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;

  const queryOptions = { initialData: null, queryKey: ["cache-test"], staleTime: 60000 };
  const first = renderHook(() => useAdminQuery(fetcher, queryOptions), { wrapper });

  await waitFor(() => {
    expect(first.result.current.data).toEqual({ value: 1 });
  });

  renderHook(() => useAdminQuery(fetcher, queryOptions), { wrapper });

  await waitFor(() => {
    expect(fetcher).toHaveBeenCalledTimes(1);
  });

  queryClient.clear();
});
