/**
 * 错误码常量表 — 按契约§0
 * 前端统一查此表，不硬编码字符串码
 */

export const ERROR_CODES = {
  SUCCESS: 0,
  PARAM_INVALID: 40001,
  UNAUTHENTICATED: 40101,
  FORBIDDEN: 40301,
  NOT_FOUND: 40401,
  STATE_CONFLICT: 40901,
  BUSINESS_VALIDATION: 42201,
  SERVER_ERROR: 50001,
  AI_CALL_FAILED: 50002,
} as const;

export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];

export interface ErrorAction {
  message: string;
  /** 前端操作提示 */
  hint: string;
  /** 'redirect' | 'banner' | 'inline' | 'toast' | 'refresh' */
  display: string;
  redirectTo?: string;
}

/** 所有错误统一查此表，违禁词/限速等细分信息从 response.message 读 */
export const errorCodeMap: Record<number, ErrorAction> = {
  [ERROR_CODES.PARAM_INVALID]: {
    message: '参数校验失败',
    hint: '请检查表单填写',
    display: 'inline',
  },
  [ERROR_CODES.UNAUTHENTICATED]: {
    message: '登录已失效',
    hint: '正在自动重新登录...',
    display: 'toast',
    redirectTo: '/login',
  },
  [ERROR_CODES.FORBIDDEN]: {
    message: '无权访问',
    hint: '您没有访问此工作区的权限',
    display: 'banner',
    redirectTo: '/dashboard',
  },
  [ERROR_CODES.NOT_FOUND]: {
    message: '资源不存在',
    hint: '请刷新页面后重试',
    display: 'toast',
  },
  [ERROR_CODES.STATE_CONFLICT]: {
    message: '当前状态不可操作',
    hint: '任务状态已变更，请刷新查看最新状态',
    display: 'toast',
  },
  [ERROR_CODES.BUSINESS_VALIDATION]: {
    message: '操作校验失败',
    hint: '请检查是否已配置 API Key，或文案包含违禁词',
    display: 'banner',
  },
  [ERROR_CODES.SERVER_ERROR]: {
    message: '服务器错误',
    hint: '生成失败，请重试',
    display: 'toast',
  },
  [ERROR_CODES.AI_CALL_FAILED]: {
    message: '生图通道繁忙',
    hint: '当前 AI 服务繁忙，请稍后重试',
    display: 'banner',
  },
};

export function getErrorAction(code: number): ErrorAction {
  return (
    errorCodeMap[code] ?? {
      message: '未知错误',
      hint: `错误码：${code}，请联系管理员`,
      display: 'toast',
    }
  );
}
