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

export function useExecutionLogs() {
  const logs = ref([])
  const loading = ref(false)
  const error = ref(null)

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

  async function fetchBySession(sessionId) {
    loading.value = true
    error.value = null
    try {
      logs.value = await executionLogRepository.getBySessionId(sessionId)
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

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

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

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

  async function getCountByDateRange(from, to) {
    return executionLogRepository.getCountByDateRange(from, to)
  }

  async function removeByDateRange(from, to) {
    await executionLogRepository.deleteByDateRange(from, to)
    await fetchAll()
  }

  return {
    logs,
    loading,
    error,
    fetchAll,
    fetchBySession,
    create,
    remove,
    getById,
    getCountByDateRange,
    removeByDateRange,
  }
}
