/**
 * 统一 API 响应包装
 *
 * 与 Dart 的 `NetResult<T>` 对应：
 * - 成功：`{ success: true, data: T }`
 * - 失败：`{ success: false, error: ApiError }`
 */
export type ApiResult<T> =
  | { success: true; data: T }
  | { success: false; error: ApiError };

/**
 * API 错误类
 */
export class ApiError extends Error {
  readonly code: string;
  readonly status?: number;
  readonly details?: unknown;

  constructor(
    code: string,
    message: string,
    status?: number,
    details?: unknown
  ) {
    super(message);
    this.name = "ApiError";
    this.code = code;
    this.status = status;
    this.details = details;
    Object.freeze(this);
  }

  /**
   * 转换为 JSON 字符串
   */
  override toString(): string {
    const statusStr = this.status !== undefined ? ` [${this.status}]` : "";
    return `${this.name}${statusStr} ${this.code}: ${this.message}`;
  }
}

/**
 * 错误码常量
 */
export class ErrorCode {
  private constructor() {}

  static readonly httpUnauthorized = 401;
  static readonly httpForbidden = 403;
  static readonly httpNotFound = 404;
  static readonly httpServerError = 500;
  static readonly httpBadRequest = 400;

  static readonly networkError = "NETWORK_ERROR";
  static readonly timeoutError = "TIMEOUT_ERROR";
  static readonly parseError = "PARSE_ERROR";
  static readonly unknownError = "UNKNOWN_ERROR";
}
