import { queryOptions, useQuery } from '@tanstack/react-query';

import { QueryConfig } from '../../../lib/reactQuery';
import { api } from '../../../lib/apiClient';
import { ProductResponse } from '../types/api';

type ProductsQueryParams = {
    search?: string | null;
    page?: number;
    limit?: number;
};

export const getProducts = ({ search, page, limit }: ProductsQueryParams): Promise<ProductResponse> => {
    return api.get('/inventory/products', {
        params: {
            search,
            page,
            limit,
        },
    });
};

export const getProductsQueryOptions = ({ search, page, limit }: ProductsQueryParams) => {
    return queryOptions({
        queryKey: ['products', { search, page, limit }],
        queryFn: () => getProducts({ search, page, limit }),
    });
};

type UseProductsOptions = {
    queryConfig?: QueryConfig<typeof getProductsQueryOptions>;
} & ProductsQueryParams;

export const useProducts = ({ search, page, limit, queryConfig }: UseProductsOptions = {}) => {
    return useQuery({
        ...getProductsQueryOptions({ search, page, limit }),
        ...queryConfig,
    });
};
