interface SkillApiErrorShape {
  code?: number | string;
  error?: string;
  errorCode?: number | string;
  httpStatus?: number | string;
  message?: string;
  response?: {
    data?: unknown;
    status?: number | string;
  };
  status?: number | string;
}

function errorSnapshot(error: unknown) {
  const source = (error || {}) as SkillApiErrorShape;
  const body =
    source.response?.data && typeof source.response.data === 'object'
      ? (source.response.data as SkillApiErrorShape)
      : source;
  return {
    code: body.code,
    errorCode: Number(body.errorCode),
    message: String(body.message || body.error || ''),
    status: Number(
      source.response?.status ?? body.httpStatus ?? body.status ?? 0,
    ),
  };
}

/** 返回 Skill 请求中可直接展示的错误信息。 */
export function resolveSkillApiErrorMessage(error: unknown, fallback: string) {
  return errorSnapshot(error).message || fallback;
}

/** 判断文件请求是否因乐观锁冲突失败。 */
export function isSkillFileConflictError(error: unknown) {
  const snapshot = errorSnapshot(error);
  return (
    snapshot.status === 409 ||
    snapshot.errorCode === 4091 ||
    snapshot.code === 'SKILL_FILE_CONFLICT' ||
    snapshot.message.includes('已被其他操作更新')
  );
}

/** 判断能力配置请求是否因版本冲突失败。 */
export function isSkillCapabilityConflictError(error: unknown) {
  const snapshot = errorSnapshot(error);
  return (
    snapshot.status === 409 ||
    snapshot.errorCode === 4093 ||
    snapshot.message.includes('能力配置已被其他操作更新')
  );
}

/** 判断 Skill 请求是否被服务端以未登录或无权限拒绝。 */
export function isSkillAccessDeniedError(error: unknown) {
  const snapshot = errorSnapshot(error);
  return (
    snapshot.status === 401 ||
    snapshot.status === 403 ||
    snapshot.errorCode === 401 ||
    snapshot.errorCode === 403
  );
}
