import { defineStore } from 'pinia'
import { ref } from 'vue'
import { gardensApi, type Garden } from '@/api/gardens'

export const useGardensStore = defineStore('gardens', () => {
  const gardens = ref<Garden[]>([])
  const loading = ref(false)

  async function fetchAll() {
    loading.value = true
    gardens.value = await gardensApi.list()
    loading.value = false
  }

  async function create(g: Partial<Garden>) {
    const created = await gardensApi.create(g)
    gardens.value.push(created)
    return created
  }

  async function update(id: number, g: Partial<Garden>) {
    const updated = await gardensApi.update(id, g)
    const idx = gardens.value.findIndex(x => x.id === id)
    if (idx !== -1) gardens.value[idx] = updated
    return updated
  }

  async function remove(id: number) {
    await gardensApi.delete(id)
    gardens.value = gardens.value.filter(g => g.id !== id)
  }

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