import 'package:p_tits_pas/models/parent_child_summary.dart'; import 'package:p_tits_pas/models/user.dart'; class ParentModel { final AppUser user; final AppUser? coParent; final int childrenCount; final List children; ParentModel({ required this.user, this.coParent, this.childrenCount = 0, this.children = const [], }); factory ParentModel.fromJson(Map json) { final root = Map.from(json); final userJson = Map.from(root['user'] ?? root); if (root['numero_dossier'] != null && userJson['numero_dossier'] == null) { userJson['numero_dossier'] = root['numero_dossier']; } final user = AppUser.fromJson(userJson); AppUser? coParent; final coParentRaw = root['co_parent']; if (coParentRaw is Map) { coParent = AppUser.fromJson(Map.from(coParentRaw)); } final children = _parseChildren(root); final links = root['parentChildren'] ?? root['parent_children']; final linkCount = links is List ? links.length : 0; return ParentModel( user: user, coParent: coParent, childrenCount: children.isNotEmpty ? children.length : linkCount, children: children, ); } static List _parseChildren(Map json) { final children = []; final seen = {}; void add(ParentChildSummary? child) { if (child == null || child.id.isEmpty || seen.contains(child.id)) return; seen.add(child.id); children.add(child); } final links = json['parentChildren'] ?? json['parent_children']; if (links is List) { for (final link in links) { if (link is! Map) continue; add(ParentChildSummary.fromParentChildLink( Map.from(link), )); } } return children; } }