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

/// 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().catchError((e) {
            debugPrint('Update failed: $e');
          });
        }
      }
    } 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();
        }
      }
    } catch (e) {
      debugPrint('Immediate update error: $e');
    }
  }
}
