/// 版本信息
class VersionInfo {
  /// 版本代码（数字）
  final int versionCode;

  /// 版本名称（如 1.2.3）
  final String versionName;

  /// 构建号
  final String buildNumber;

  /// 下载地址
  final String downloadUrl;

  /// 文件大小（字节）
  final int fileSize;

  /// SHA256 校验和
  final String fileSha256;

  /// 更新日志
  final String changelog;

  /// 是否强制更新
  final bool isForceUpdate;

  /// 最低支持的系统版本
  final String? minOsVersion;

  /// 发布日期
  final DateTime? releaseDate;

  const VersionInfo({
    required this.versionCode,
    required this.versionName,
    required this.buildNumber,
    required this.downloadUrl,
    required this.fileSize,
    required this.fileSha256,
    required this.changelog,
    this.isForceUpdate = false,
    this.minOsVersion,
    this.releaseDate,
  });

  factory VersionInfo.fromJson(Map<String, dynamic> json) {
    return VersionInfo(
      versionCode: json['versionCode'] as int,
      versionName: json['versionName'] as String,
      buildNumber: json['buildNumber'] as String,
      downloadUrl: json['downloadUrl'] as String,
      fileSize: json['fileSize'] is String
          ? int.parse(json['fileSize'])
          : json['fileSize'] as int,
      fileSha256: json['fileSha256'] as String,
      changelog: json['changelog'] as String,
      isForceUpdate: json['isForceUpdate'] as bool? ?? false,
      minOsVersion: json['minOsVersion'] as String?,
      releaseDate: json['releaseDate'] != null
          ? DateTime.tryParse(json['releaseDate'] as String)
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'versionCode': versionCode,
      'versionName': versionName,
      'buildNumber': buildNumber,
      'downloadUrl': downloadUrl,
      'fileSize': fileSize,
      'fileSha256': fileSha256,
      'changelog': changelog,
      'isForceUpdate': isForceUpdate,
      'minOsVersion': minOsVersion,
      'releaseDate': releaseDate?.toIso8601String(),
    };
  }

  /// 格式化文件大小
  String get formattedFileSize {
    if (fileSize < 1024) {
      return '$fileSize B';
    } else if (fileSize < 1024 * 1024) {
      return '${(fileSize / 1024).toStringAsFixed(1)} KB';
    } else if (fileSize < 1024 * 1024 * 1024) {
      return '${(fileSize / (1024 * 1024)).toStringAsFixed(1)} MB';
    } else {
      return '${(fileSize / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
    }
  }
}

/// 更新检查结果
class UpdateCheckResult {
  /// 是否有更新
  final bool hasUpdate;

  /// 新版本信息
  final VersionInfo? versionInfo;

  /// 错误信息
  final String? error;

  const UpdateCheckResult({
    required this.hasUpdate,
    this.versionInfo,
    this.error,
  });

  factory UpdateCheckResult.noUpdate() {
    return const UpdateCheckResult(hasUpdate: false);
  }

  factory UpdateCheckResult.hasUpdate(VersionInfo info) {
    return UpdateCheckResult(hasUpdate: true, versionInfo: info);
  }

  factory UpdateCheckResult.error(String message) {
    return UpdateCheckResult(hasUpdate: false, error: message);
  }
}
