import { ref } from 'vue'
import { api } from '../api/client'
import { useToast } from './useToast'

export function useSaveLiterature() {
  const isSaving = ref(false)

  async function toggleSave(pmid: number, isSaved: boolean): Promise<boolean> {
    isSaving.value = true
    const toast = useToast()
    try {
      if (isSaved) {
        await api.delete(`/literature/${pmid}/save`)
        toast.success('已取消收藏')
        return false
      } else {
        await api.post(`/literature/${pmid}/save`)
        toast.success('已收藏')
        return true
      }
    } catch (e) {
      toast.apiError(e, '操作失败')
      return isSaved
    } finally {
      isSaving.value = false
    }
  }

  return { isSaving, toggleSave }
}
