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

export const updateProduct = ({ data, productId }: { data: UpdateProductFormValues; productId: number }): Promise<Product> => {
    return api.put(`/inventory/products/${productId}`, data);
};

type UseUpdateProductOptions = {
    mutationConfig?: MutationConfig<typeof updateProduct>;
};

export const useUpdateProduct = ({ mutationConfig }: UseUpdateProductOptions = {}) => {
    const queryClient = useQueryClient();

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

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