import { useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';

import { getDraftPermissions } from 'src/services/posts';

import { postDraftKeys } from '../queries';

type Props = {
  checkBoth?: boolean;
  checkDrafter?: boolean;
  onSuccess?: (res: boolean) => void;
};

export const useCheckDraftPermission = (props: Props) => {
  const { checkBoth = false, checkDrafter = false, onSuccess } = props;

  const navigate = useNavigate();

  const { data: canCreateDraft, isFetching: draftPermissionsIsLoading } =
    useQuery(
      postDraftKeys.mine(),
      ({ pageParam = '' }) =>
        getDraftPermissions({
          limit: 1,
          cursor: pageParam,
          type: 'FOR_CREATION',
        }),
      {
        enabled: checkBoth || checkDrafter,
        select: res => res.data.items.length > 0,
        onSuccess,
      },
    );

  const { data: isFinalAuthor, isFetching: draftPermissionsAuthorIsLoading } =
    useQuery(
      postDraftKeys.finalAuthor(),
      ({ pageParam = '' }) =>
        getDraftPermissions({
          limit: 1,
          cursor: pageParam,
          type: 'AS_END_USER',
        }),
      {
        enabled: checkBoth,
        select: res => res.data.items.length > 0,
      },
    );

  if (
    !draftPermissionsAuthorIsLoading &&
    !draftPermissionsIsLoading &&
    ((checkDrafter && !canCreateDraft) ||
      (checkBoth && !canCreateDraft && !isFinalAuthor))
  ) {
    navigate('/');
  }

  return {
    canCreateDraft,
    isFinalAuthor,
    draftPermissionsIsLoading,
    draftPermissionsAuthorIsLoading,
  };
};
