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

export const createProductCategory = ({ data }: { data: CreateProductCategoryFormValues }): Promise<ProductCategory> => {
    return api.post('/inventory/categories', data);
};

type UseCreateProductCategoryOptions = {
    mutationConfig?: MutationConfig<typeof createProductCategory>;
};

export const useCreateProductCategory = ({ mutationConfig }: UseCreateProductCategoryOptions = {}) => {
    const queryClient = useQueryClient();

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

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