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

export function useExercises() {
  const exercises = ref([])
  const loading = ref(false)
  const error = ref(null)

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

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

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

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

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

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

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