/** 后端统计原始返回（type/status 可能为 number 或 string，count 为整数） */
export type FeedbackStatResponse = {
  total: number;
  typeCounts?: Array<{ type: string | number; count: number }> | null;
  statusCounts?: Array<{ status: string | number; count: number }> | null;
};

/** 后端统计原始返回 → 业务层（type/status 一律 String 化为 Record 键，count 缺省兜底 0；data 为空全兜底 0） */
export function normalizeFeedbackStat(data: FeedbackStatResponse | null | undefined): Api.Feedback.FeedbackStat {
  const typeCounts: Record<string, number> = {};
  (data?.typeCounts ?? []).forEach(item => {
    typeCounts[String(item.type)] = item.count ?? 0;
  });

  const statusCounts: Record<string, number> = {};
  (data?.statusCounts ?? []).forEach(item => {
    statusCounts[String(item.status)] = item.count ?? 0;
  });

  const total = data?.total ?? 0;

  // 契约约定 total == sum(typeCounts) == sum(statusCounts)；dev 下做一致性自检，便于尽早发现后端统计口径错位
  if (import.meta.env.DEV) {
    const typeSum = Object.values(typeCounts).reduce((sum, count) => sum + count, 0);
    const statusSum = Object.values(statusCounts).reduce((sum, count) => sum + count, 0);
    if (total !== typeSum || total !== statusSum) {
      console.warn(
        `[feedback-stat] total=${total} 与分类合计=${typeSum}、状态合计=${statusSum} 不一致，后端统计口径可能有误`
      );
    }
  }

  return { total, typeCounts, statusCounts };
}
