import { MutationCache, QueryClient } from "@tanstack/react-query";

import type { InvalidatesMeta } from "@/utils/endpoint";

/**
 * Single app-wide React Query client (do not nest additional providers).
 *
 * Declarative invalidation: any mutation built via `api.*.mutationOptions()`
 * (see `services/api.ts` + `utils/endpoint.ts`) carries an `invalidates`
 * function in its `meta`. The shared `MutationCache` below runs it on success
 * and invalidates the returned query keys — so invalidation is declared once in
 * the endpoint definition rather than re-wired in every component.
 */
export const queryClient = new QueryClient({
  mutationCache: new MutationCache({
    onSuccess: (data, variables, _context, mutation) => {
      const invalidates = mutation.meta?.invalidates as
        | InvalidatesMeta
        | undefined;
      if (typeof invalidates !== "function") return;

      for (const queryKey of invalidates(variables, data)) {
        void queryClient.invalidateQueries({ queryKey });
      }
    },
  }),
  defaultOptions: {
    queries: {
      retry: 1,
      refetchOnWindowFocus: false,
      staleTime: 30_000,
    },
  },
});
