import { reflectionApi, type MonitorConfigPayload } from '@/api/reflection'

/** 进程内缓存：避免每次选中车辆都 GET /monitor-config（全量反射扫描，极慢）。 */
let cached: MonitorConfigPayload | null = null
let inflight: Promise<MonitorConfigPayload> | null = null

export function invalidateMonitorConfigCache(): void {
  cached = null
  inflight = null
}

export async function fetchMonitorConfigCached(force = false): Promise<MonitorConfigPayload> {
  if (!force && cached) return cached
  if (!force && inflight) return inflight
  inflight = reflectionApi.getMonitorConfig().then((mc) => {
    cached = mc
    inflight = null
    return mc
  }).catch((e) => {
    inflight = null
    throw e
  })
  return inflight
}
