export class HaloError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode?: number,
    public readonly originalError?: unknown,
  ) {
    super(message);
    this.name = "HaloError";
  }

  static network(error: unknown): HaloError {
    return new HaloError("网络请求失败，请检查网络连接", "NETWORK_ERROR", undefined, error);
  }

  static unauthorized(): HaloError {
    return new HaloError("认证失败，请检查 Token 是否有效", "UNAUTHORIZED", 401);
  }

  static forbidden(): HaloError {
    return new HaloError("权限不足，无法执行此操作", "FORBIDDEN", 403);
  }

  static notFound(resource: string): HaloError {
    return new HaloError(`${resource} 未找到`, "NOT_FOUND", 404);
  }

  static serverError(message = "服务器错误"): HaloError {
    return new HaloError(message, "SERVER_ERROR", 500);
  }

  static validationError(message: string): HaloError {
    return new HaloError(message, "VALIDATION_ERROR");
  }

  static unknown(error: unknown): HaloError {
    const message = error instanceof Error ? error.message : "未知错误";
    return new HaloError(message, "UNKNOWN", undefined, error);
  }

  isNetworkError(): boolean {
    return this.code === "NETWORK_ERROR";
  }

  isAuthError(): boolean {
    return this.code === "UNAUTHORIZED" || this.code === "FORBIDDEN";
  }

  isNotFound(): boolean {
    return this.code === "NOT_FOUND";
  }
}

export class HttpError extends Error {
  constructor(
    public readonly statusCode: number,
    message: string,
    public readonly response?: unknown,
  ) {
    super(message);
    this.name = "HttpError";
  }

  static fromStatus(statusCode: number, response?: unknown): HttpError {
    const messages: Record<number, string> = {
      400: "请求参数错误",
      401: "认证失败",
      403: "权限不足",
      404: "资源不存在",
      500: "服务器内部错误",
    };
    const message = messages[statusCode] || `HTTP 错误 (${statusCode})`;
    return new HttpError(statusCode, message, response);
  }
}
