import { ref, onMounted, onBeforeUnmount } from 'vue'

export function usePolling(fetchFn, intervalMs = 10_000) {
  const data = ref(null)
  const loading = ref(false)
  const error = ref(null)
  let timer = null

  async function poll() {
    loading.value = true
    try {
      data.value = await fetchFn()
      error.value = null
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  function start() {
    poll()
    timer = setInterval(poll, intervalMs)
  }

  function stop() {
    if (timer) clearInterval(timer)
    timer = null
  }

  onMounted(start)
  onBeforeUnmount(stop)

  return { data, loading, error, poll, stop }
}