import { ref } from 'vue'
import { api } from '../api/client'
import { useToast } from './useToast'
import type { PersonalTag } from '../types'
import type { Ref } from 'vue'

export function usePersonalTags(pmid: number, personalTags: Ref<PersonalTag[]>) {
  const toast = useToast()
  const newTag = ref('')

  async function handleAddTag() {
    if (!newTag.value.trim()) return
    try {
      const { data } = await api.post(`/settings/literature/${pmid}/tag`, { tag: newTag.value })
      personalTags.value = data.personal_tags || []
      newTag.value = ''
    } catch (e) { toast.apiError(e, '添加标签失败，请重试') }
  }

  async function handleRemoveTag(tagName: string) {
    try {
      await api.delete(`/settings/literature/${pmid}/tag?tag_name=${encodeURIComponent(tagName)}`)
      personalTags.value = personalTags.value.filter((t: PersonalTag) => t.name !== tagName)
    } catch (e) { toast.apiError(e, '删除标签失败，请重试') }
  }

  return { newTag, handleAddTag, handleRemoveTag }
}
