import { defineStore } from 'pinia'
import { ref } from 'vue'
import { plantsApi, type Plant } from '@/api/plants'

export const usePlantsStore = defineStore('plants', () => {
  const plants = ref<Plant[]>([])
  const loading = ref(false)

  async function fetchAll(categorie?: string) {
    loading.value = true
    try { plants.value = await plantsApi.list(categorie) }
    finally { loading.value = false }
  }

  async function create(p: Partial<Plant>) {
    const created = await plantsApi.create(p)
    plants.value.push(created)
    return created
  }

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

  return { plants, loading, fetchAll, create, remove }
})
