import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getHealth } from '@/api/modules/system'
import type { HealthMetrics } from '@/types'

/**
 * 顶部栏系统监控 store
 * 30s 轮询 CPU/内存/磁盘使用率
 */
export const useSystemStore = defineStore('system', () => {
  const metrics = ref<HealthMetrics>({})
  let timer: ReturnType<typeof setInterval> | null = null
  let fetching = false

  async function fetchMetrics() {
    if (fetching || document.hidden) return
    fetching = true
    try {
      metrics.value = await getHealth()
    } catch {
      // 静默失败，顶部栏非关键
    } finally {
      fetching = false
    }
  }

  function handleVisibilityChange() {
    if (!document.hidden) void fetchMetrics()
  }

  function start() {
    if (timer) return
    void fetchMetrics()
    timer = setInterval(fetchMetrics, 30000)
    document.addEventListener('visibilitychange', handleVisibilityChange)
  }

  function stop() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    document.removeEventListener('visibilitychange', handleVisibilityChange)
  }

  return { metrics, fetchMetrics, start, stop }
})
