import { QueryClient, QueryKey } from "@tanstack/react-query";
import { ServerResult } from "../types";

export async function ensureServerQueryData<TData>(
  queryClient: QueryClient,
  query: {
    queryKey: QueryKey;
    queryFn: () => Promise<ServerResult<TData>>;
  }
): Promise<TData> {
  return queryClient.ensureQueryData({
    queryKey: query.queryKey,
    queryFn: async () => {
      const result = await query.queryFn();
      
      if (!result.success) {
        throw new Error(result.error.userMessage);
      }
      
      return result.data;
    }
  });
}