import { QueryKey, UseQueryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { ServerResult } from "../types";
import toast from '@/lib/sonner'

export function useServerSuspenseQuery<TData>(
  options: {
      queryKey: QueryKey,
      queryFn: () => Promise<ServerResult<TData>>;
      options?: Omit<UseQueryOptions<TData, Error, TData>, 'queryFn' | 'queryKey'>
      showErrorToast?: boolean;
  }
) {
  const { queryKey, queryFn, showErrorToast = true, options: queryOptions } = options;
  const queryResult = useSuspenseQuery({
    ...queryOptions,
    queryKey,
    queryFn: async () => {
      const result = await queryFn();
      
      if (!result.success) {
        if (showErrorToast) {
          toast.error(result.error.userMessage);
        }
        throw new Error(result.error.userMessage);
      }
      
      return result.data;
    }
  });

  return queryResult;
}