// 服务器实例的状态映射（本地业务态 + 上游电源态）。
// 多处复用：ServerList、ServerDetail 等。

export interface StatusMeta {
  label: string
  bg: string
  text: string
  dot: string
}

const FALLBACK: StatusMeta = { label: "未知", bg: "bg-gray-100", text: "text-gray-600", dot: "bg-gray-400" }

// 本地业务状态（数据库 Instance.status）
export const STATUS_META: Record<string, StatusMeta> = {
  provisioning:     { label: "开通中",  bg: "bg-amber-50",   text: "text-amber-700",   dot: "bg-amber-400 animate-pulse" },
  active:           { label: "运行中",  bg: "bg-emerald-50", text: "text-emerald-700", dot: "bg-emerald-500" },
  suspended:        { label: "已暂停",  bg: "bg-orange-50",  text: "text-orange-700",  dot: "bg-orange-400" },
  terminated:       { label: "已销毁",  bg: "bg-slate-100",  text: "text-slate-500",   dot: "bg-slate-400" },
  failed:           { label: "开通失败", bg: "bg-red-50",    text: "text-red-700",     dot: "bg-red-500" },
  provision_failed: { label: "待处理",  bg: "bg-red-50",    text: "text-red-700",     dot: "bg-red-500" },
}

// 上游魔方云电源态
export const UPSTREAM_POWER_META: Record<string, StatusMeta> = {
  on:           { label: "运行中",  bg: "bg-emerald-50", text: "text-emerald-700", dot: "bg-emerald-500" },
  off:          { label: "已关机",  bg: "bg-slate-100",  text: "text-slate-600",   dot: "bg-slate-400" },
  init:         { label: "创建中",  bg: "bg-amber-50",   text: "text-amber-700",   dot: "bg-amber-400 animate-pulse" },
  wait_reboot:  { label: "等待重启", bg: "bg-sky-50",    text: "text-sky-700",     dot: "bg-sky-400 animate-pulse" },
  wait:         { label: "等待中",  bg: "bg-sky-50",    text: "text-sky-700",     dot: "bg-sky-400 animate-pulse" },
  suspend:      { label: "已暂停",  bg: "bg-orange-50", text: "text-orange-700",  dot: "bg-orange-400" },
  paused:       { label: "已挂起",  bg: "bg-orange-50", text: "text-orange-700",  dot: "bg-orange-400" },
  unknown:      { label: "未知",    bg: "bg-gray-100",  text: "text-gray-500",    dot: "bg-gray-400" },
}

/** 优先用上游电源态（如有），否则用业务态；都没命中时返回 fallback。 */
export function resolveStatusMeta(businessStatus: string | null | undefined, upstreamStatus?: string | null): StatusMeta {
  if (businessStatus && businessStatus !== "active") {
    return STATUS_META[businessStatus] ?? { ...FALLBACK, label: businessStatus }
  }
  if (upstreamStatus) {
    const key = upstreamStatus.toLowerCase()
    if (UPSTREAM_POWER_META[key]) return UPSTREAM_POWER_META[key]
  }
  if (businessStatus && STATUS_META[businessStatus]) return STATUS_META[businessStatus]
  return FALLBACK
}
