import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../lib/apiClient';
import { MutationConfig } from '../../../lib/reactQuery';
import { UpdateProductCategoryFormValues } from '../types/form';
import { getProductCategoriesQueryOptions } from './getProductCategories';
import { ProductCategory } from '../types/api';

export const updateProductCategory = ({ data, categoryId }: { data: UpdateProductCategoryFormValues; categoryId: number }): Promise<ProductCategory> => {
    return api.put(`/inventory/categories/${categoryId}`, data);
};

type UseUpdateProductCategoryOptions = {
    mutationConfig?: MutationConfig<typeof updateProductCategory>;
};

export const useUpdateProductCategory = ({ mutationConfig }: UseUpdateProductCategoryOptions = {}) => {
    const queryClient = useQueryClient();

    const { onSuccess, ...restConfig } = mutationConfig || {};

    return useMutation({
        mutationFn: updateProductCategory,
        onSuccess: (data, ...args) => {
            queryClient.invalidateQueries({
                queryKey: getProductCategoriesQueryOptions().queryKey,
            });
            onSuccess?.(data, ...args);
        },
        ...restConfig,
    });
};
