// errors.ts — 错误码 → 双语文案映射表（阶段 B 落地）
import { ApiError } from './types';
import type { Lang } from '../i18n';

/**
 * 后端统一返回 {code, message_zh, message_en}；前端优先用后端文案,
 * 兜底用本表(后端文案缺失/网络层错误时)。codes 与 #1 openapi 对齐。
 */
export const ERROR_TEXT: Record<string, { zh: string; en: string }> = {
  invalid_credentials: { zh: '邮箱或密码错误', en: 'Wrong email or password' },
  rate_limited: { zh: '操作过于频繁,请稍后再试', en: 'Too many requests, slow down' },
  account_locked: { zh: '失败次数过多,账户已临时锁定', en: 'Too many attempts — account temporarily locked' },
  totp_required: { zh: '需要双重认证动态码', en: 'Two-factor code required' },
  totp_invalid: { zh: '动态码不正确,请重试', en: 'Invalid code, try again' },
  code_invalid: { zh: '激活码无效', en: 'Invalid activation code' },
  code_used: { zh: '激活码已被使用', en: 'Activation code already used' },
  code_expired: { zh: '激活码已过期', en: 'Activation code expired' },
  device_limit: { zh: '设备数量已达上限', en: 'Device limit reached' },
  device_not_found: { zh: '设备不存在', en: 'Device not found' },
  unauthorized: { zh: '登录已失效,请重新登录', en: 'Session expired, please log in again' },
  network: { zh: '网络异常,请稍后重试', en: 'Network error, please retry' },
  unknown: { zh: '操作失败,请稍后重试', en: 'Something went wrong, please retry' },
};

/** 把任意错误转成当前语言文案(后端文案优先,再查表,最后 unknown) */
export function bilingual(err: unknown, lang: Lang): string {
  if (err instanceof ApiError) {
    const fromServer = lang === 'zh' ? err.message_zh : err.message_en;
    if (fromServer) return fromServer;
    const m = ERROR_TEXT[err.code];
    if (m) return m[lang];
  }
  return ERROR_TEXT.unknown[lang];
}
