import { ref } from 'vue'

/**
 * Factory for the four identical CRUD composables (exercises, combos,
 * sessions, collections). Returns a composable exposing the reactive item
 * list under `itemsKey` plus the shared loading/error/CRUD API, so
 * useExercises & co. stay one-liners with unchanged call sites.
 */
export function createCrudComposable(repository, itemsKey) {
  return function useCrud() {
    const items = ref([])
    const loading = ref(false)
    const error = ref(null)

    async function fetchAll() {
      loading.value = true
      error.value = null
      try {
        items.value = await repository.getAll()
      } catch (e) {
        error.value = e.message
      } finally {
        loading.value = false
      }
    }

    async function create(data) {
      const id = await repository.create(data)
      await fetchAll()
      return id
    }

    async function update(id, data) {
      await repository.update(id, data)
      await fetchAll()
    }

    async function remove(id) {
      await repository.delete(id)
      await fetchAll()
    }

    async function search(query) {
      loading.value = true
      error.value = null
      try {
        items.value = await repository.search(query)
      } catch (e) {
        error.value = e.message
      } finally {
        loading.value = false
      }
    }

    async function getById(id) {
      return repository.getById(id)
    }

    return {
      [itemsKey]: items,
      loading,
      error,
      fetchAll,
      create,
      update,
      remove,
      search,
      getById,
    }
  }
}
