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

export function useMangaEdit() {
    const mangaRepository = new ApiMangaRepository();
    const queryClient = useQueryClient();
    const isEditModalOpen = ref(false);

    const editMutation = useMutation({
        mutationFn: ({ mangaId, updateData }) => {
            return mangaRepository.editManga(mangaId, updateData);
        },
        onSuccess: (data, variables) => {
            // Invalider et refetch les données du manga
            queryClient.invalidateQueries({ queryKey: ['manga', variables.mangaId] });
            queryClient.invalidateQueries({ queryKey: ['mangas'] });
        }
    });

    const openEditModal = () => {
        isEditModalOpen.value = true;
    };

    const closeEditModal = () => {
        isEditModalOpen.value = false;
    };

    const editManga = async (mangaId, updateData) => {
        try {
            await editMutation.mutateAsync({ mangaId, updateData });
            closeEditModal();
        } catch (error) {
            console.error('Erreur lors de l\'édition du manga:', error);
            throw error;
        }
    };

    return {
        isEditModalOpen,
        openEditModal,
        closeEditModal,
        editManga,
        isLoading: editMutation.isPending,
        error: editMutation.error,
        isSuccess: editMutation.isSuccess
    };
}
