import 'package:freezed_annotation/freezed_annotation.dart';

part 'api_error.freezed.dart';

/// API 统一错误类型（Freezed 联合类型）
@freezed
class ApiError with _$ApiError implements Exception {
  const factory ApiError.noNetworkConnection() = _NoNetworkConnection;
  const factory ApiError.timeout() = _Timeout;
  const factory ApiError.networkError(String message) = _NetworkError;
  const factory ApiError.decodingError(String message) = _DecodingError;
  const factory ApiError.apiError({
    required int code,
    required String message,
  }) = _ApiError;

  /// 请求被 CancelToken 取消
  const factory ApiError.cancelled() = _Cancelled;
  const factory ApiError.unknown(String? message) = _Unknown;
}

/// 错误类型扩展 - 提供用户可读的错误描述
extension ApiErrorExtension on ApiError {
  String get displayMessage {
    return when(
      noNetworkConnection: () => 'No network connection',
      timeout: () => 'Request timeout',
      networkError: (message) => 'Network error: $message',
      decodingError: (message) => 'Decoding error: $message',
      apiError: (code, message) => message,
      cancelled: () => 'Request cancelled',
      unknown: (message) => message ?? 'Unknown error',
    );
  }
}
