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

/**
 * Reference data no website mutation changes: option lists, the CMS payload
 * and server settings. Left fresh so a write does not refetch every dropdown.
 */
const REFERENCE_ROOTS: ReadonlySet<string> = new Set([
  "dropdown",
  "dropdownChoices",
  "home-cms",
  "faqs",
  "banner-images",
  "trainer-request-settings",
  "check-license-requirement",
]);

export function isReferenceQuery(queryKey: readonly unknown[]): boolean {
  const root = queryKey[0];
  return typeof root === "string" && (REFERENCE_ROOTS.has(root) || root.endsWith("-choices"));
}

/**
 * The safety net under every mutation's own refresh. With a one-minute
 * `staleTime`, a write refreshed only the keys its screen named: a
 * registration, cancellation, edit or deletion left the profile tabs, counters,
 * home sections and other lists showing pre-write data until the minute ran
 * out. Each success now marks every server read stale *without* refetching
 * it (`refetchType: "none"`), so nothing on the current screen reloads under
 * the user — whatever a screen shows next is read again on mount.
 */
export function markServerReadsStale(queryClient: Pick<QueryClient, "invalidateQueries">): Promise<void> {
  return queryClient.invalidateQueries({
    refetchType: "none",
    predicate: (query) => !isReferenceQuery(query.queryKey),
  });
}

/** The app's QueryClient: the given defaults plus the stale-marking net above. */
export function createAppQueryClient(config: Omit<QueryClientConfig, "mutationCache"> = {}): QueryClient {
  const client: QueryClient = new QueryClient({
    ...config,
    mutationCache: new MutationCache({
      onSuccess: () => {
        void markServerReadsStale(client);
      },
    }),
  });
  return client;
}
