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

export function useCollections() {
  const collections = ref([])
  const loading = ref(false)
  const error = ref(null)

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

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

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

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

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

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

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