import { computed, onMounted, onUnmounted, ref } from 'vue'
import type { KbxOperationRun, KbxRuntimeNotice, KbxUserNotification } from '@kbx/contracts'
import { runtimeApi } from './runtimeApi'

export function useKbxRuntime() {
  const notice = ref<KbxRuntimeNotice | null>(null)
  const operations = ref<KbxOperationRun[]>([])
  const notifications = ref<KbxUserNotification[]>([])
  let timer: ReturnType<typeof setInterval> | undefined

  async function refresh() {
    const [nextNotice, nextOperations, nextNotifications] = await Promise.all([
      runtimeApi.getNotice(),
      runtimeApi.getOperations(),
      runtimeApi.getNotifications(),
    ])
    notice.value = nextNotice
    operations.value = nextOperations
    notifications.value = nextNotifications
  }

  async function markRead(id: string) {
    await runtimeApi.markNotificationRead(id)
    const item = notifications.value.find(x => x.id === id)
    if (item && !item.readAt) item.readAt = new Date().toISOString()
  }

  onMounted(() => {
    void refresh()
    timer = setInterval(() => void refresh(), 30_000)
  })
  onUnmounted(() => { if (timer) clearInterval(timer) })

  return {
    notice,
    operations,
    notifications,
    unreadCount: computed(() => notifications.value.filter(x => !x.readAt).length),
    refresh,
    markRead,
  }
}
