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

export function useMangaPreferredSources(mangaId) {
    const mangaRepository = new ApiMangaRepository();
    const queryClient = useQueryClient();

    // Query pour récupérer les sources préférées
    const preferredSourcesQuery = useQuery({
        queryKey: ['manga', mangaId, 'preferred-sources'],
        queryFn: () => {
            if (!mangaId.value) {
                return Promise.resolve(null);
            }
            return mangaRepository.getPreferredSources(mangaId.value);
        },
        enabled: computed(() => !!mangaId.value)
    });

    // Mutation pour sauvegarder les sources préférées
    const setPreferredSourcesMutation = useMutation({
        mutationFn: ({ sourceIds }) => {
            return mangaRepository.setPreferredSources(mangaId.value, sourceIds);
        },
        onSuccess: () => {
            // Invalider le cache pour refaire la requête de récupération
            queryClient.invalidateQueries({
                queryKey: ['manga', mangaId.value, 'preferred-sources']
            });
        }
    });

    const sources = computed(() => preferredSourcesQuery.data.value?.sources || []);
    const hasPreferredSources = computed(() => preferredSourcesQuery.data.value?.hasPreferredSources || false);
    const isLoading = computed(() => preferredSourcesQuery.isLoading.value);
    const error = computed(() => preferredSourcesQuery.error.value);
    const isSaving = computed(() => setPreferredSourcesMutation.isPending.value);

    const savePreferredSources = (sourceIds) => {
        return setPreferredSourcesMutation.mutate({ sourceIds });
    };

    return {
        sources,
        hasPreferredSources,
        isLoading,
        error,
        isSaving,
        savePreferredSources
    };
}
