import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../lib/apiClient';
import { MutationConfig } from '../../../lib/reactQuery';
import { UpdateProductCollectionFormValues } from '../types/form';
import { ProductCollection } from '../types/api';
import { getProductCollectionsQueryOptions } from './getProductCollections';

export const updateProductCollection = ({ data, collectionId }: { data: UpdateProductCollectionFormValues; collectionId: number }): Promise<ProductCollection> => {
    return api.put(`/inventory/collections/${collectionId}`, data);
};

type UseUpdateProductCollectionOptions = {
    mutationConfig?: MutationConfig<typeof updateProductCollection>;
};

export const useUpdateProductCollection = ({ mutationConfig }: UseUpdateProductCollectionOptions = {}) => {
    const queryClient = useQueryClient();

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

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