import { api } from '@/utils/request'
import type { MqStatusData, MqQueueType, MqQueueInfo } from '@/types/api'

export const useMqStatusStore = defineStore('mqStatus', () => {
  const statusData = ref<MqStatusData | null>(null)
  const loading = ref(false)
  const errorMessage = ref('')
  const queueType = ref<MqQueueType | undefined>(undefined)

  const healthySummary = computed(() => {
    if (!statusData.value) return { healthy: 0, total: 0 }
    const allQueues: MqQueueInfo[] = [
      ...statusData.value.business_queues,
      ...statusData.value.retry_queues,
      ...(!Array.isArray(statusData.value.error_queue) ? [statusData.value.error_queue] : []),
    ]
    const healthy = allQueues.filter(
      (q) => q.status === 'active' || q.status === 'empty',
    ).length
    return { healthy, total: allQueues.length }
  })

  async function fetchStatus() {
    loading.value = true
    errorMessage.value = ''
    try {
      const params: Record<string, unknown> = {}
      if (queueType.value) {
        params.queue = queueType.value
      }
      const data = await api.get<MqStatusData>('/api/v1/mq/status', params)
      statusData.value = data
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : '获取 MQ 状态失败'
      errorMessage.value = msg
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  function resetFilter() {
    queueType.value = undefined
  }

  return {
    statusData,
    loading,
    errorMessage,
    queueType,
    healthySummary,
    fetchStatus,
    resetFilter,
  }
})
