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

export interface Favorite {
  id?: number
  project_id: number
  task_id?: number | null
  description?: string | null
  sort_order: number
}

export const useFavoritesStore = defineStore('favorites', () => {
  const favorites = ref<Favorite[]>([])

  async function fetchFavorites() {
    try {
      favorites.value = await invoke<Favorite[]>('get_favorites')
    } catch (error) {
      handleInvokeError(error, 'Failed to fetch favorites', () => fetchFavorites())
    }
  }

  async function createFavorite(fav: Favorite): Promise<number | null> {
    try {
      const id = await invoke<number>('create_favorite', { fav })
      favorites.value.push({ ...fav, id: Number(id) })
      return Number(id)
    } catch (error) {
      handleInvokeError(error, 'Failed to create favorite')
      return null
    }
  }

  async function deleteFavorite(id: number): Promise<boolean> {
    try {
      await invoke('delete_favorite', { id })
      favorites.value = favorites.value.filter(f => f.id !== id)
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to delete favorite')
      return false
    }
  }

  async function reorderFavorites(ids: number[]): Promise<boolean> {
    const oldOrder = [...favorites.value]
    favorites.value = ids
      .map(id => favorites.value.find(f => f.id === id))
      .filter((f): f is Favorite => f !== undefined)
    try {
      await invoke('reorder_favorites', { ids })
      return true
    } catch (error) {
      favorites.value = oldOrder
      handleInvokeError(error, 'Failed to reorder favorites')
      return false
    }
  }

  return { favorites, fetchFavorites, createFavorite, deleteFavorite, reorderFavorites }
})
