import { defineStore } from 'pinia'
import { ref } from 'vue'
import { plantingsApi, type Planting } from '@/api/plantings'

export const usePlantingsStore = defineStore('plantings', () => {
  const plantings = ref<Planting[]>([])
  const loading = ref(false)

  async function fetchAll() {
    loading.value = true
    plantings.value = await plantingsApi.list()
    loading.value = false
  }

  async function create(p: Partial<Planting>) {
    const created = await plantingsApi.create(p)
    plantings.value.push(created)
    return created
  }

  async function update(id: number, p: Partial<Planting>) {
    const updated = await plantingsApi.update(id, p)
    const idx = plantings.value.findIndex(x => x.id === id)
    if (idx !== -1) plantings.value[idx] = updated
    return updated
  }

  async function remove(id: number) {
    await plantingsApi.delete(id)
    plantings.value = plantings.value.filter(p => p.id !== id)
  }

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