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

/// 待办操作检查结果
class PendingActionCheckResult {
  /// 是否有待办操作
  final bool hasPendingActions;

  /// 待办操作数量
  final int pendingCount;

  /// 下一个待办操作
  final PendingAction? nextAction;

  PendingActionCheckResult({
    required this.hasPendingActions,
    required this.pendingCount,
    this.nextAction,
  });
}

/// 待办操作检查服务
/// 用于在 App 启动时检查用户是否有待办操作需要执行
class PendingActionCheckService {
  final PendingActionService _pendingActionService;

  PendingActionCheckService({
    required PendingActionService pendingActionService,
  }) : _pendingActionService = pendingActionService;

  /// 检查是否有待办操作
  /// 返回 true 表示有待办操作，需要强制执行
  Future<bool> hasPendingActions() async {
    try {
      final response = await _pendingActionService.getMyPendingActions();
      return response.hasPendingActions;
    } catch (e) {
      debugPrint('[PendingActionCheckService] 检查待办操作失败: $e');
      // 检查失败时不阻止用户使用 App
      return false;
    }
  }

  /// 综合检查待办操作
  Future<PendingActionCheckResult> check() async {
    try {
      final response = await _pendingActionService.getMyPendingActions();
      final pendingActions = response.pendingActionsSorted;

      debugPrint('[PendingActionCheckService] 检测到 ${pendingActions.length} 个待办操作');

      return PendingActionCheckResult(
        hasPendingActions: pendingActions.isNotEmpty,
        pendingCount: pendingActions.length,
        nextAction: response.nextAction,
      );
    } catch (e) {
      debugPrint('[PendingActionCheckService] 综合检查失败: $e');
      // 检查失败时不阻止用户使用 App
      return PendingActionCheckResult(
        hasPendingActions: false,
        pendingCount: 0,
      );
    }
  }

  /// 获取待办操作数量
  Future<int> getPendingActionCount() async {
    try {
      final response = await _pendingActionService.getMyPendingActions();
      return response.pendingActionsSorted.length;
    } catch (e) {
      debugPrint('[PendingActionCheckService] 获取待办操作数量失败: $e');
      return 0;
    }
  }
}
