import { defineStore } from 'pinia'
import { ref } from 'vue'
import { tasksApi, type Task } from '@/api/tasks'

export const useTasksStore = defineStore('tasks', () => {
  const tasks = ref<Task[]>([])
  const loading = ref(false)

  async function fetchAll(params?: { statut?: string; garden_id?: number }) {
    loading.value = true
    tasks.value = await tasksApi.list(params)
    loading.value = false
  }

  async function create(t: Partial<Task>) {
    const created = await tasksApi.create(t)
    tasks.value.push(created)
    return created
  }

  async function update(id: number, data: Partial<Task>) {
    const updated = await tasksApi.update(id, data)
    const idx = tasks.value.findIndex(t => t.id === id)
    if (idx !== -1) tasks.value[idx] = updated
    return updated
  }

  async function updateStatut(id: number, statut: string) {
    const t = tasks.value.find(t => t.id === id)
    if (!t) return
    const updated = await tasksApi.update(id, { ...t, statut })
    Object.assign(t, updated)
  }

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

  return { tasks, loading, fetchAll, create, update, updateStatut, remove }
})
