import type { AdminPlayTypeRow } from "@/types/api/admin-config";

let cachedByCode = new Map<string, AdminPlayTypeRow>();
let inflightLoad: Promise<void> | null = null;

export function getCachedAdminPlayType(playCode: string): AdminPlayTypeRow | undefined {
  return cachedByCode.get(playCode);
}

export function getCachedAdminPlayTypes(): AdminPlayTypeRow[] {
  return [...cachedByCode.values()];
}

export function setCachedAdminPlayTypes(items: AdminPlayTypeRow[]): void {
  cachedByCode = new Map(items.map((row) => [row.play_code, row]));
}

export function clearCachedAdminPlayTypes(): void {
  cachedByCode = new Map();
  inflightLoad = null;
}

export function getAdminPlayTypesLoadPromise(
  loader: () => Promise<{ items: AdminPlayTypeRow[] }>,
): Promise<void> {
  if (cachedByCode.size > 0) {
    return Promise.resolve();
  }
  if (inflightLoad !== null) {
    return inflightLoad;
  }

  inflightLoad = loader()
    .then((data) => {
      setCachedAdminPlayTypes(data.items);
    })
    .catch(() => {
      // 玩法目录加载失败时回退展示 play_code，不阻断页面。
    })
    .finally(() => {
      inflightLoad = null;
    });

  return inflightLoad;
}

/** 确保玩法目录已加载并返回缓存列表（全局去重，配置页勿直接 getAdminPlayTypes） */
export async function ensureAdminPlayTypesLoaded(
  loader: () => Promise<{ items: AdminPlayTypeRow[] }>,
): Promise<AdminPlayTypeRow[]> {
  await getAdminPlayTypesLoadPromise(loader);
  return getCachedAdminPlayTypes();
}

/** 解析玩法显示名；无配置时回退 play_code */
export function resolveAdminPlayTypeDisplayName(
  playCode: string | null | undefined,
  _language?: string,
  row?: AdminPlayTypeRow,
): string {
  if (playCode == null || playCode === "") {
    return "—";
  }

  const resolved = row ?? cachedByCode.get(playCode);
  if (!resolved) {
    return playCode;
  }

  const name = resolved.display_name?.trim();
  return name ? name : playCode;
}

/** 表格展示：显示名 + 编码（与报表筛选一致） */
export function formatAdminPlayCodeLabel(
  playCode: string | null | undefined,
  language?: string,
): string {
  if (playCode == null || playCode === "") {
    return "—";
  }

  const name = resolveAdminPlayTypeDisplayName(playCode, language);
  if (name === playCode) {
    return playCode;
  }

  return `${name} (${playCode})`;
}
