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

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

type ProductsQueryParams = {
    q?: string;
    page?: number;
    limit?: number;
};

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

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

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

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