import 'package:superport_v2/core/permissions/permission_manager.dart';

import '../domain/entities/group_permission.dart';
import '../domain/mappers/group_permission_mapper.dart';
import '../domain/repositories/group_permission_repository.dart';

/// 서버에서 그룹 메뉴 권한을 조회해 [PermissionManager]에 반영하는 동기화기.
class PermissionSynchronizer {
  PermissionSynchronizer({
    required GroupPermissionRepository repository,
    required PermissionManager manager,
    this.pageSize = 200,
  }) : _repository = repository,
       _manager = manager;

  final GroupPermissionRepository _repository;
  final PermissionManager _manager;
  final int pageSize;

  /// 지정한 [groupId]의 메뉴 권한을 조회해 [PermissionManager]에 적용한다.
  Future<void> syncForGroup(int groupId) async {
    final permissionMap = await fetchPermissionMap(groupId);
    _manager.applyServerPermissions(permissionMap);
  }

  /// 지정한 [groupId]의 메뉴 권한을 조회해 맵 형태로 반환한다.
  Future<Map<String, Set<PermissionAction>>> fetchPermissionMap(
    int groupId,
  ) async {
    final collected = await _collectPermissions(groupId);
    if (collected.isEmpty) {
      return const {};
    }
    return buildPermissionMap(collected);
  }

  Future<List<GroupPermission>> _collectPermissions(int groupId) async {
    final collected = <GroupPermission>[];
    var page = 1;

    while (true) {
      final response = await _repository.list(
        page: page,
        pageSize: pageSize,
        groupId: groupId,
        includeDeleted: false,
        isActive: true,
      );
      collected.addAll(response.items);

      final currentPageSize = response.pageSize == 0
          ? response.items.length
          : response.pageSize;
      if (currentPageSize == 0) {
        break;
      }
      final fetched = page * currentPageSize;
      if (fetched >= response.total) {
        break;
      }
      page += 1;
    }

    return collected;
  }
}
