import { ref } from 'vue'
import { fetchServerList } from '@/api/ops/server'

export type LabeledNumberOption = { label: string; value: number }
export type LabeledStringOption = { label: string; value: string }

function unwrapListRes(res: unknown): { data: any[]; total: number } {
  const r = res as Record<string, any> | null | undefined
  const d = r?.details ?? r
  return {
    data: Array.isArray(d?.data) ? d.data : [],
    total: typeof d?.total === 'number' ? d.total : 0,
  }
}

/** 服务器报表：按 ID / 按标识 下拉选项 */
export function useReportServerPickOptions() {
  const serverIdOptions = ref<LabeledNumberOption[]>([])
  const serverIdentityOptions = ref<LabeledStringOption[]>([])
  const serverOptionsLoading = ref(false)

  async function loadServerPickOptions() {
    serverIdOptions.value = []
    serverIdentityOptions.value = []
    serverOptionsLoading.value = true
    try {
      const pageSize = 500
      let page = 1
      const idAcc: LabeledNumberOption[] = []
      const identAcc: LabeledStringOption[] = []

      while (true) {
        const res = await fetchServerList({ page, size: pageSize })
        const u = unwrapListRes(res)
        const chunk = u.data
        const total = u.total
        for (const s of chunk) {
          const id = s?.id
          const name = (s?.name as string) || ''
          const ident = (s?.server_identity as string) || ''
          if (typeof id === 'number') {
            idAcc.push({
              label: ident ? `${name || ident} (ID: ${id})` : `服务器 #${id}`,
              value: id,
            })
          }
          if (ident) {
            identAcc.push({
              label: name ? `${name} (${ident})` : ident,
              value: ident,
            })
          }
        }
        if (chunk.length === 0 || chunk.length < pageSize) break
        if (total > 0 && idAcc.length >= total) break
        page += 1
      }
      serverIdOptions.value = idAcc
      serverIdentityOptions.value = identAcc
    } catch (e) {
      console.error('加载服务器选项失败:', e)
      serverIdOptions.value = []
      serverIdentityOptions.value = []
    } finally {
      serverOptionsLoading.value = false
    }
  }

  return {
    serverIdOptions,
    serverIdentityOptions,
    serverOptionsLoading,
    loadServerPickOptions,
  }
}
