import {useState} from 'react';
import {getPostTranslation} from '@modules/post/services';
import {getTranslatedGroupPost} from '@modules/group/services';

interface UseTranslationFetchOptions {
  groupId?: number;
  postId: number;
}

export const useTranslationFetch = ({
  groupId,
  postId,
}: UseTranslationFetchOptions) => {
  const [translation, setTranslation] = useState<string>('');
  const [isTranslating, setIsTranslating] = useState(false);

  const fetchTranslation = async () => {
    if (isTranslating) {
      return;
    }
    setIsTranslating(true);
    try {
      const data = await (groupId
        ? getTranslatedGroupPost({groupId, postId})
        : getPostTranslation(postId));
      setTranslation(data.body);
    } finally {
      setIsTranslating(false);
    }
  };

  return {
    translation,
    isTranslating,
    fetchTranslation,
  };
};
