import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../lib/apiClient';
import { MutationConfig } from '../../../lib/reactQuery';
import { UpdateProductSizeFormValues } from '../types/form';
import { ProductSize } from '../types/api';
import { getProductSizesQueryOptions } from './getProductSizes';

export const updateProductSize = ({ data, sizeId }: { data: UpdateProductSizeFormValues; sizeId: number }): Promise<ProductSize> => {
    return api.put(`/inventory/sizes/${sizeId}`, data);
};

type UseUpdateProductSizeOptions = {
    mutationConfig?: MutationConfig<typeof updateProductSize>;
};

export const useUpdateProductSize = ({ mutationConfig }: UseUpdateProductSizeOptions = {}) => {
    const queryClient = useQueryClient();

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

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