import 'package:in_app_update/in_app_update.dart';
import 'package:flutter/foundation.dart';

/// Google Play 应用内更新类型
enum GooglePlayUpdateType {
  /// 灵活更新：后台下载，可继续使用
  flexible,

  /// 强制更新：阻塞式，必须更新
  immediate,
}

/// Google Play 应用内更新器
class GooglePlayUpdater {
  /// 检查是否有更新可用
  static Future<bool> checkForUpdate() async {
    try {
      final updateInfo = await InAppUpdate.checkForUpdate();
      return updateInfo.updateAvailability ==
          UpdateAvailability.updateAvailable;
    } catch (e) {
      debugPrint('Check update failed: $e');
      return false;
    }
  }

  /// 灵活更新
  /// 用户可以在后台下载，继续使用应用
  static Future<void> performFlexibleUpdate() async {
    try {
      final updateInfo = await InAppUpdate.checkForUpdate();

      if (updateInfo.updateAvailability == UpdateAvailability.updateAvailable) {
        if (updateInfo.flexibleUpdateAllowed) {
          await InAppUpdate.startFlexibleUpdate();

          InAppUpdate.completeFlexibleUpdate().then((_) {
            debugPrint('Update completed, app will restart');
          }).catchError((e) {
            debugPrint('Update failed: $e');
          });
        } else {
          debugPrint('Flexible update not allowed');
        }
      }
    } catch (e) {
      debugPrint('Flexible update error: $e');
    }
  }

  /// 强制更新
  /// 阻塞式更新，用户必须更新才能继续使用
  static Future<void> performImmediateUpdate() async {
    try {
      final updateInfo = await InAppUpdate.checkForUpdate();

      if (updateInfo.updateAvailability == UpdateAvailability.updateAvailable) {
        if (updateInfo.immediateUpdateAllowed) {
          await InAppUpdate.performImmediateUpdate();
        } else {
          debugPrint('Immediate update not allowed');
        }
      }
    } catch (e) {
      debugPrint('Immediate update error: $e');
    }
  }

  /// 智能更新策略
  /// 根据版本差异决定更新方式
  static Future<void> smartUpdate({
    required int currentVersion,
    required int latestVersion,
  }) async {
    final versionDiff = latestVersion - currentVersion;

    if (versionDiff >= 10) {
      // 版本差异大，强制更新
      await performImmediateUpdate();
    } else {
      // 版本差异小，灵活更新
      await performFlexibleUpdate();
    }
  }
}
