import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../lib/apiClient';
import { MutationConfig } from '../../../lib/reactQuery';
import { CreateProductFormValues } from '../types/form';
import { getProductsQueryOptions } from './getProducts';
import { Product } from '../types/api';

export const createProduct = ({ data }: { data: CreateProductFormValues }): Promise<Product> => {
    return api.post('/inventory/products', data);
};

type UseCreateProductOptions = {
    mutationConfig?: MutationConfig<typeof createProduct>;
};

export const useCreateProduct = ({ mutationConfig }: UseCreateProductOptions = {}) => {
    const queryClient = useQueryClient();

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

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