import { defineStore } from 'pinia'
import { ref } from 'vue'
import { toolsApi, type Tool } from '@/api/tools'

export const useToolsStore = defineStore('tools', () => {
  const tools = ref<Tool[]>([])
  const loading = ref(false)

  async function fetchAll() {
    loading.value = true
    try { tools.value = await toolsApi.list() }
    finally { loading.value = false }
  }

  async function create(t: Partial<Tool>) {
    const created = await toolsApi.create(t)
    tools.value.push(created)
    return created
  }

  async function update(id: number, t: Partial<Tool>) {
    const updated = await toolsApi.update(id, t)
    const idx = tools.value.findIndex(x => x.id === id)
    if (idx !== -1) tools.value[idx] = updated
    return updated
  }

  async function remove(id: number) {
    await toolsApi.delete(id)
    tools.value = tools.value.filter(t => t.id !== id)
  }

  return { tools, loading, fetchAll, create, update, remove }
})
