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

import '../entities/group_permission.dart';

/// 그룹-메뉴 권한 목록을 [PermissionManager]에 적용할 수 있는 맵으로 변환한다.
///
/// - 메뉴 경로([GroupPermissionMenu.path])가 비어 있으면 해당 항목은 건너뛴다.
/// - 읽기 권한은 [PermissionAction.view]로 매핑하고, CRUD 권한은 각각 대응한다.
Map<String, Set<PermissionAction>> buildPermissionMap(
  Iterable<GroupPermission> permissions,
) {
  final result = <String, Set<PermissionAction>>{};
  for (final permission in permissions) {
    final path = PermissionResources.normalize(permission.menu.path ?? '');
    if (path.isEmpty) {
      continue;
    }
    final actions = result.putIfAbsent(path, () => <PermissionAction>{});
    if (permission.canRead) {
      actions.add(PermissionAction.view);
    }
    if (permission.canCreate) {
      actions.add(PermissionAction.create);
    }
    if (permission.canUpdate) {
      actions.add(PermissionAction.edit);
    }
    if (permission.canDelete) {
      actions.add(PermissionAction.delete);
    }
  }
  return result;
}
