import { ref, type Ref } from 'vue'
import { http } from '@/api'
import { CACHE_KEYS, cachedFetch, invalidateCachedQuery } from '@/composables/useCachedQuery'

export const SERVER_STAT_CARD_KEYS = [
  'total',
  'online',
  'offline',
  'unset-path',
  'alerts',
] as const

export type ServerStatCardKey = (typeof SERVER_STAT_CARD_KEYS)[number]

export interface ServerStatCardItem {
  subtitle: string
  title: string
  icon: string
  color: string
}

export interface ServerStatsResponse {
  total: number
  online: number
  offline: number
  online_list?: number
  offline_list?: number
  unset_path: number
  alerts: number
  categories?: Record<string, number>
}

export function createServerStatItems(): ServerStatCardItem[] {
  return [
    { subtitle: '服务器总数', title: '0', icon: 'mdi-server-network', color: 'blue' },
    { subtitle: '在线', title: '0', icon: 'mdi-check-circle-outline', color: 'green' },
    { subtitle: '离线', title: '0', icon: 'mdi-alert-circle-outline', color: 'orange' },
    { subtitle: '未设路径', title: '0', icon: 'mdi-folder-off-outline', color: 'amber' },
    { subtitle: '告警中', title: '0', icon: 'mdi-bell-alert-outline', color: 'red' },
  ]
}

/** 与服务器页顶部统计卡一致：在线=全库 Agent，离线=主列表 offline_list */
export function applyServerStats(
  statItems: Ref<ServerStatCardItem[]>,
  s: ServerStatsResponse,
): void {
  statItems.value[0].title = String(s.total)
  statItems.value[1].title = String(s.online)
  statItems.value[2].title = String(s.offline_list ?? s.offline)
  statItems.value[3].title = String(s.unset_path ?? 0)
  statItems.value[4].title = String(s.alerts ?? 0)
}

export async function fetchServerStats(): Promise<ServerStatsResponse> {
  const { data } = await cachedFetch(CACHE_KEYS.serverStats, () =>
    http.get<ServerStatsResponse>('/servers/stats'),
  )
  return data
}

/** 强制跳过缓存拉取并写回统计卡数字 */
export async function refreshServerStats(
  statItems: Ref<ServerStatCardItem[]>,
): Promise<ServerStatsResponse> {
  invalidateCachedQuery(CACHE_KEYS.serverStats)
  const s = await fetchServerStats()
  applyServerStats(statItems, s)
  return s
}

export function useServerStatsCards() {
  const statItems = ref(createServerStatItems())
  return { statItems }
}
