import {
  useQuery,
  keepPreviousData,
  useQueryClient,
} from "@tanstack/react-query";
import type { UseQueryOptions } from "@tanstack/react-query";

interface PaginatedResult<T> {
  data: T[];
  pagination: {
    total: number;
    page: number;
    per_page: number;
    total_pages: number;
  };
}

/**
 * Wrapper around useQuery for paginated list endpoints.
 * Accepts the return value of queryOptions() from lib/queries/*
 * and extracts items + pagination from the response.
 *
 * `options` is intentionally `any`: the query helpers pass a `queryOptions(...)`
 * object whose `queryKey` is a concrete mutable tuple, and TanStack's `enabled`
 * predicate is contravariant in the key type — pinning the key generic here
 * (even via an inferred `TKey`) fails to unify for several callers. The data
 * shape we rely on (`PaginatedResult<T>`) is enforced by the cast below, so the
 * loss of input typing on `options` is contained to this thin wrapper.
 */
export function usePaginatedQuery<T>(
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  options: any,
) {
  const query = useQuery({
    ...options,
    placeholderData: keepPreviousData,
  } as UseQueryOptions<PaginatedResult<T>>);

  const data = query.data as PaginatedResult<T> | undefined;

  return {
    items: (data?.data ?? []) as T[],
    pagination: data?.pagination ?? null,
    isPending: query.isPending,
    isFetching: query.isFetching,
    isPlaceholderData: query.isPlaceholderData,
    isError: query.isError,
    error: query.error,
    refetch: query.refetch,
  };
}

export { useQueryClient, useQuery, keepPreviousData };
