import { useMutation, useQueryClient } from '@tanstack/vue-query';
import { ref } from 'vue';
import { ApiMangaRepository } from '../../infrastructure/api/apiMangaRepository';

export function useMangaDelete() {
    const mangaRepository = new ApiMangaRepository();
    const queryClient = useQueryClient();
    const isDeleteModalOpen = ref(false);

    const deleteMutation = useMutation({
        mutationFn: ({ mangaId }) => {
            return mangaRepository.deleteManga(mangaId);
        },
        onSuccess: (data, variables) => {
            // Invalider et refetch les listes de mangas
            queryClient.invalidateQueries({ queryKey: ['mangas'] });
            queryClient.invalidateQueries({ queryKey: ['manga-search'] });
        }
    });

    const openDeleteModal = () => {
        isDeleteModalOpen.value = true;
    };

    const closeDeleteModal = () => {
        isDeleteModalOpen.value = false;
    };

    const deleteManga = async (mangaId) => {
        try {
            await deleteMutation.mutateAsync({ mangaId });
            closeDeleteModal();
            return true;
        } catch (error) {
            console.error('Erreur lors de la suppression du manga:', error);
            throw error;
        }
    };

    return {
        isDeleteModalOpen,
        openDeleteModal,
        closeDeleteModal,
        deleteManga,
        isLoading: deleteMutation.isPending,
        error: deleteMutation.error,
        isSuccess: deleteMutation.isSuccess
    };
}
