/**
 * 图谱重建任务轮询组合式函数
 * 封装定时轮询重建任务状态的逻辑，组件卸载时自动停止。
 */
import { ref, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import { getRebuildStatus } from '@/api/admin-graph'
import type { RebuildStatusResponse } from '@/types/admin-graph'

export function useRebuildPolling(onCompleted?: () => void) {
  const rebuildTask = ref<RebuildStatusResponse>({
    task_id: '',
    status: '',
    progress: 0,
    current: 0,
    total: 0,
    current_doc_id: '',
  })

  let pollTimer: ReturnType<typeof setInterval> | null = null

  /** 启动轮询，每 3 秒查询一次重建状态 */
  function startPolling() {
    stopPolling()
    pollTimer = setInterval(async () => {
      if (!rebuildTask.value.task_id) return
      try {
        const status = await getRebuildStatus(rebuildTask.value.task_id)
        rebuildTask.value = status
        if (status.status === 'COMPLETED' || status.status === 'FAILED') {
          stopPolling()
          if (status.status === 'COMPLETED') {
            message.success('重建完成')
            onCompleted?.()
          } else {
            message.error('重建失败: ' + (status.error || ''))
          }
        }
      } catch {
        // 忽略轮询错误
      }
    }, 3000)
  }

  /** 停止轮询 */
  function stopPolling() {
    if (pollTimer) {
      clearInterval(pollTimer)
      pollTimer = null
    }
  }

  onUnmounted(() => {
    stopPolling()
  })

  return {
    rebuildTask,
    startPolling,
    stopPolling,
  }
}
