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

export function useSessions() {
  const sessions = ref([])
  const loading = ref(false)
  const error = ref(null)

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

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

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

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

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

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

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