import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../lib/apiClient';
import { MutationConfig } from '../../../lib/reactQuery';
import { ProductColour } from '../types/api';
import { getProductColoursQueryOptions } from './getProductColours';
import { UpdateProductColourFormValues } from '../types/form';

export const updateProductColour = ({ data, colourId }: { data: UpdateProductColourFormValues; colourId: number }): Promise<ProductColour> => {
    return api.put(`/inventory/colours/${colourId}`, data);
};

type UseUpdateProductColourOptions = {
    mutationConfig?: MutationConfig<typeof updateProductColour>;
};

export const useUpdateProductColour = ({ mutationConfig }: UseUpdateProductColourOptions = {}) => {
    const queryClient = useQueryClient();

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

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