import { onMounted, onUnmounted, ref } from 'vue'
import { notificationsApi } from '@/api/notifications'
import { useNotificationsStore } from '@/stores/notifications'

const POLL_INTERVAL_MS = 30_000

export function useUnreadPoller() {
  const store = useNotificationsStore()
  let timer: ReturnType<typeof setInterval> | null = null
  const error = ref<string | null>(null)

  async function refresh() {
    try {
      const { count } = await notificationsApi.unreadCount()
      store.setUnreadCount(count)
    } catch (e) {
      error.value = String(e)
    }
  }

  function start() {
    if (timer !== null) return
    refresh()
    timer = setInterval(refresh, POLL_INTERVAL_MS)
  }

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

  function onVisibilityChange() {
    if (document.hidden) {
      stop()
    } else {
      start()
    }
  }

  onMounted(() => {
    start()
    document.addEventListener('visibilitychange', onVisibilityChange)
  })

  onUnmounted(() => {
    document.removeEventListener('visibilitychange', onVisibilityChange)
    stop()
  })

  return { refresh, error }
}
