import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as api from '../lib/api';

export function useComments(params: api.FindCommentsParams = {}) {
  return useQuery({
    queryKey: ['comments', params],
    queryFn: () => api.fetchComments(params),
  });
}

export function useCreateComment() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: api.createComment,
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ 
        queryKey: ['comments', { articleId: variables.articleId }] 
      });
      queryClient.invalidateQueries({ 
        queryKey: ['comments', { liveBlogId: variables.liveBlogId }] 
      });
    },
  });
}

export function useUpdateComment() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: api.UpdateCommentDto }) =>
      api.updateComment(id, dto),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['comments'] });
    },
  });
}

export function useDeleteComment() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: api.deleteComment,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['comments'] });
    },
  });
}

export function useReactionCounts(
  articleId?: string,
  liveBlogId?: string,
  commentId?: string
) {
  return useQuery({
    queryKey: ['reactions', 'counts', { articleId, liveBlogId, commentId }],
    queryFn: () => api.getReactionCounts(articleId, liveBlogId, commentId),
    enabled: !!articleId || !!liveBlogId || !!commentId,
  });
}

export function useUserReaction(
  articleId?: string,
  liveBlogId?: string,
  commentId?: string
) {
  return useQuery({
    queryKey: ['reactions', 'user', { articleId, liveBlogId, commentId }],
    queryFn: () => api.getUserReaction(articleId, liveBlogId, commentId),
    enabled: !!articleId || !!liveBlogId || !!commentId,
    retry: false,
  });
}

export function useAddReaction() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: api.addReaction,
    onSuccess: (_, variables) => {
      // Invalidate both counts and user reaction queries
      queryClient.invalidateQueries({ 
        queryKey: ['reactions', 'counts', { 
          articleId: variables.articleId,
          liveBlogId: variables.liveBlogId,
          commentId: variables.commentId
        }] 
      });
      queryClient.invalidateQueries({ 
        queryKey: ['reactions', 'user', { 
          articleId: variables.articleId,
          liveBlogId: variables.liveBlogId,
          commentId: variables.commentId
        }] 
      });
    },
  });
}