import { useQuery } from 'react-query';

import { usePaginatedQueryState } from 'src/hooks/usePaginatedQueryState';
import { type RequestError, type RequestSuccess } from 'src/types/services';

import { type GetProductsParams } from '../Exchanges/types';
import { acknowledgementsKeys } from '../queries';
import { getProducts } from '../services';

export type TSuccess = RequestSuccess<typeof getProducts>;
export type TError = RequestError;
export type TData = TSuccess['data'];

export const useGetProducts = (params: GetProductsParams) => {
  const { data, ...query } = useQuery<TSuccess, TError, TData>({
    queryKey: acknowledgementsKeys.products(params),
    queryFn: () => getProducts(params),
    select: response => response.data,
    keepPreviousData: true,
  });

  const products = (data?.items ?? []).map(item => item.product);
  const totalPages = data?.totalPages ?? 0;

  const queryState = usePaginatedQueryState(data, query.status);

  return {
    ...query,
    ...queryState,
    products,
    totalPages,
  };
};
