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<ParentChildSummary> children;

  ParentModel({
    required this.user,
    this.coParent,
    this.childrenCount = 0,
    this.children = const [],
  });

  factory ParentModel.fromJson(Map<String, dynamic> json) {
    final root = Map<String, dynamic>.from(json);
    final userJson = Map<String, dynamic>.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<String, dynamic>.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<ParentChildSummary> _parseChildren(Map<String, dynamic> json) {
    final children = <ParentChildSummary>[];
    final seen = <String>{};

    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<String, dynamic>.from(link),
        ));
      }
    }

    return children;
  }
}
