import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { publicationService } from '../services/publicationService';

export const usePublications = (page: number = 1, pageSize: number = 10) => {
  return useQuery({
    queryKey: ['publications', page, pageSize],
    queryFn: () => publicationService.getPublications(page, pageSize),
    keepPreviousData: true,
  });
};

export const usePublication = (id: number) => {
  return useQuery({
    queryKey: ['publication', id],
    queryFn: () => publicationService.getPublication(id),
    enabled: !!id,
  });
};

export const usePublicationSteps = (publicationId: number) => {
  return useQuery({
    queryKey: ['publication-steps', publicationId],
    queryFn: () => publicationService.getPublicationSteps(publicationId),
    enabled: !!publicationId,
  });
};

export const useActivePublications = () => {
  return useQuery({
    queryKey: ['active-publications'],
    queryFn: () => publicationService.getActivePublications(),
    refetchInterval: 5000, // Refresh every 5 seconds for active publications
  });
};

export const useCancelPublication = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (id: number) => publicationService.cancelPublication(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['publications'] });
      queryClient.invalidateQueries({ queryKey: ['active-publications'] });
    },
  });
};

export const useRetryPublication = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (id: number) => publicationService.retryPublication(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['publications'] });
      queryClient.invalidateQueries({ queryKey: ['active-publications'] });
    },
  });
};