import { ref } from 'vue'
import { comboRepository } from '../db/repositories/comboRepository.js'

export function useCombos() {
  const combos = ref([])
  const loading = ref(false)
  const error = ref(null)

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

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

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

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

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

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

  return { combos, loading, error, fetchAll, create, update, remove, search, getById }
}
