/// API 响应包装解析器
/// 统一处理 { code, message/msg, data } 格式的服务器响应
class ApiResponseWrapper<T> {
  final int code;
  final String? message;
  final T? data;

  const ApiResponseWrapper({required this.code, this.message, this.data});

  factory ApiResponseWrapper.fromJson(
    Map<String, dynamic> json,
    T Function(Object?) fromJsonT,
  ) {
    // code 字段：兼容 int 和 String
    final int codeValue;
    if (json['code'] is int) {
      codeValue = json['code'] as int;
    } else if (json['code'] is String) {
      codeValue = int.tryParse(json['code'] as String) ?? 0;
    } else {
      throw FormatException(
        'Expected int or String for code, got ${json['code'].runtimeType}',
      );
    }

    // message 字段：兼容 message 和 msg
    final message = json['message'] as String? ?? json['msg'] as String?;

    // 解码 data（null-safe：logout / delete 等接口可能无 data）
    final rawData = json['data'];
    final T? decodedData = rawData != null ? fromJsonT(rawData) : null;

    return ApiResponseWrapper<T>(
      code: codeValue,
      message: message,
      data: decodedData,
    );
  }
}
