import {useQuery} from 'react-query';
import {useCursorInfinityQuery} from '@hooks/queries/useCursorInfinityQuery';
import {
  GroupUsersReactionsResponse,
  UsersReactionsResponse,
} from '@interfaces/reaction';
import {User} from '@interfaces/user';
import {getGroupCommentReactionUsers} from '@modules/group/services';
import {postQueryKeys} from '@modules/post/constants';
import {GROUP_QUERY_KEYS} from '@modules/group/constants';
import {getCommentReactions} from '@services/comment';

type ReactionResponse =
  | GroupUsersReactionsResponse
  | UsersReactionsResponse
  | {users: User[]};

export const useGetUserFromReactionComment = ({
  commentId,
  reaction,
  showReactionsSummary,
  groupId,
  postId,
}: {
  commentId: number;
  reaction: string;
  showReactionsSummary: boolean;
  groupId?: number;
  postId?: number;
}) => {
  const data = useQuery<ReactionResponse, unknown, User[]>(
    postQueryKeys.getCommentReactions({commentId, reaction, postId}),
    () => getCommentReactions({commentId, reaction}),
    {
      enabled: showReactionsSummary && !!commentId && !groupId,
      select: response => response.users,
    },
  );

  const groupData = useCursorInfinityQuery({
    queryKey: GROUP_QUERY_KEYS.getCommentReactions({
      commentId,
      reaction,
      postId,
      groupId,
    }),
    queryFn: ({cursor}) =>
      getGroupCommentReactionUsers({
        commentId,
        reaction,
        groupId: groupId!,
        postId: postId!,
        cursor,
      }),
    options: {
      enabled: showReactionsSummary && !!(commentId && groupId && postId),
    },
  });

  return groupId ? groupData : data;
};
