import { defineStore } from 'pinia'
import { ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { handleInvokeError } from '../utils/errorHandler'

export interface Tag {
  id?: number
  name: string
  color: string
}

export const useTagsStore = defineStore('tags', () => {
  const tags = ref<Tag[]>([])

  async function fetchTags() {
    try {
      tags.value = await invoke<Tag[]>('get_tags')
    } catch (error) {
      handleInvokeError(error, 'Failed to fetch tags', () => fetchTags())
    }
  }

  async function createTag(tag: Tag): Promise<number | null> {
    try {
      const id = await invoke<number>('create_tag', { tag })
      tags.value.push({ ...tag, id: Number(id) })
      return Number(id)
    } catch (error) {
      handleInvokeError(error, 'Failed to create tag')
      return null
    }
  }

  async function updateTag(tag: Tag): Promise<boolean> {
    try {
      await invoke('update_tag', { tag })
      const index = tags.value.findIndex(t => t.id === tag.id)
      if (index !== -1) tags.value[index] = tag
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to update tag')
      return false
    }
  }

  async function deleteTag(id: number): Promise<boolean> {
    try {
      await invoke('delete_tag', { id })
      tags.value = tags.value.filter(t => t.id !== id)
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to delete tag')
      return false
    }
  }

  async function getEntryTags(entryId: number): Promise<Tag[]> {
    try {
      return await invoke<Tag[]>('get_entry_tags', { entryId })
    } catch (error) {
      handleInvokeError(error, 'Failed to get entry tags')
      return []
    }
  }

  async function setEntryTags(entryId: number, tagIds: number[]): Promise<boolean> {
    try {
      await invoke('set_entry_tags', { entryId, tagIds })
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to set entry tags')
      return false
    }
  }

  return { tags, fetchTags, createTag, updateTag, deleteTag, getEntryTags, setEntryTags }
})
