import { useCallback } from 'react';

import { type AxiosResponse } from 'axios';

import { getGroupPostViewers } from 'src/services/groups';
import { getPostViewers } from 'src/services/posts';
import { type PostViewer } from 'src/types/posts';
import { type CursorPagination } from 'src/types/services';

export type PostViewersContext = 'feed' | 'groups';

export type UsePostViewersProps = {
  context: PostViewersContext;
  postId: number;
  groupId?: number | string;
};

export type GetViewersFunction = (params?: {
  limit?: number;
  cursor?: string;
  search?: string;
}) => Promise<AxiosResponse<CursorPagination<PostViewer[]>>>;

export type UsePostViewersReturn = {
  getViewers: GetViewersFunction;
};

export const usePostViewers = ({
  context,
  postId,
  groupId,
}: UsePostViewersProps): UsePostViewersReturn => {
  // Group posts can be rendered in feed context as well.
  const useGroupService =
    Boolean(groupId) && (context === 'groups' || context === 'feed');

  const getViewers: GetViewersFunction = useCallback(
    (params?: { limit?: number; cursor?: string; search?: string }) => {
      const limit = params?.limit ?? 25;
      const cursor = params?.cursor;
      const search = params?.search;

      if (useGroupService) {
        return getGroupPostViewers(
          String(groupId),
          postId,
          limit,
          cursor,
          search,
        );
      }
      return getPostViewers(postId, limit, cursor, search);
    },
    [useGroupService, postId, groupId],
  );

  return { getViewers };
};

export default usePostViewers;
