import { EssayAPIEssay, GetEssayAPI } from "@/type/wwwAPI";
import { wwwAPI } from "@/utilities/wwwAPI";
import { useQuery } from "@tanstack/react-query";
import { getDatetime } from "taehui-lib/date";
import { useLanguage } from "taehui-lib/language";

export default function useGetEssay(essayID?: string) {
  const language = useLanguage();

  return useQuery<{
    forumTitle: string;
    title: string;
    text: string;
    date: string;
    avatarID: string;
    avatarName: string;
    hitCount: number;
    essayBefore?: EssayAPIEssay;
    essayLater?: EssayAPIEssay;
  }>({
    enabled: !!essayID,
    queryKey: ["essay", essayID, language],
    queryFn: async () => {
      const { data } = await wwwAPI.get<GetEssayAPI>(`/essay/${essayID}`, {
        params: { language },
      });
      return data;
    },
    initialData: {
      forumTitle: "",
      title: "",
      text: "",
      date: getDatetime(),
      avatarID: "",
      avatarName: "",
      hitCount: 0,
      essayBefore: undefined,
      essayLater: undefined,
    },
  });
}
