import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { tagApi } from '@/api/tag'
import type { Tag } from '@/types'

export const useTagStore = defineStore('tag', () => {
  // 状态
  const tags = ref<Tag[]>([])
  const loading = ref(false)

  // 计算属性
  const sortedTags = computed(() => {
    return [...tags.value].sort((a, b) => b.count - a.count)
  })

  const tagNames = computed(() => {
    return tags.value.map(t => t.name)
  })

  // 获取标签列表
  async function fetchTags() {
    loading.value = true
    try {
      const response = await tagApi.getTags()
      if (response.success && response.data) {
        tags.value = response.data
      }
    } finally {
      loading.value = false
    }
  }

  // 重命名标签
  async function renameTag(oldName: string, newName: string) {
    const response = await tagApi.renameTag(oldName, newName)
    if (response.success) {
      const tag = tags.value.find(t => t.name === oldName)
      if (tag) {
        tag.name = newName
      }
    }
    return response
  }

  // 删除标签
  async function deleteTag(name: string) {
    const response = await tagApi.deleteTag(name)
    if (response.success) {
      tags.value = tags.value.filter(t => t.name !== name)
    }
    return response
  }

  // 合并标签
  async function mergeTags(sourceNames: string[], targetName: string) {
    const response = await tagApi.mergeTags(sourceNames, targetName)
    if (response.success) {
      await fetchTags()
    }
    return response
  }

  return {
    // 状态
    tags,
    loading,
    // 计算属性
    sortedTags,
    tagNames,
    // 方法
    fetchTags,
    renameTag,
    deleteTag,
    mergeTags
  }
})

