import { QueryKey, useQuery, UseQueryOptions } from "@tanstack/react-query";
import { useLingui } from "@lingui/react/macro";
import { ServerResult } from "../types";
import toast from '@/lib/sonner'
import { localizeServerError } from '@/lib/i18n/error-messages'

export function useServerQuery<TData>(
    options: {
      queryKey: QueryKey,
      queryFn: () => Promise<ServerResult<TData>>;
      options?: Omit<UseQueryOptions<TData, Error, TData>, 'queryFn' | 'queryKey'>
      showErrorToast?: boolean;
      enabled?: boolean;
  }
) {
  const { queryKey, queryFn, showErrorToast = true, options: queryOptions } = options;
  const { i18n } = useLingui();

  return useQuery({
    ...queryOptions,
    queryKey,
    queryFn: async () => {
      const result = await queryFn();

      if (!result.success) {
        const message = localizeServerError(i18n, result.error);
        if (showErrorToast) {
          toast.error(message);
        }
        throw new Error(message);
      }

      return result.data;
    }
  });
}