/// Modèle pour le "compte adhérent" unifié (GET /api/membres/mon-compte).
class CompteAdherentModel {
  final String numeroMembre;
  final String nomComplet;
  final String? organisationNom;
  final String? dateAdhesion;
  final String statutCompte;

  final double soldeCotisations;
  final double soldeEpargne;
  final double soldeBloque;
  final double soldeTotalDisponible;
  final double encoursCreditTotal;
  final double capaciteEmprunt;

  final int nombreCotisationsPayees;
  final int nombreCotisationsTotal;
  final int nombreCotisationsEnRetard;
  final int? tauxEngagement;

  final int nombreComptesEpargne;
  final String dateCalcul;

  const CompteAdherentModel({
    required this.numeroMembre,
    required this.nomComplet,
    this.organisationNom,
    this.dateAdhesion,
    this.statutCompte = 'ACTIF',
    this.soldeCotisations = 0,
    this.soldeEpargne = 0,
    this.soldeBloque = 0,
    this.soldeTotalDisponible = 0,
    this.encoursCreditTotal = 0,
    this.capaciteEmprunt = 0,
    this.nombreCotisationsPayees = 0,
    this.nombreCotisationsTotal = 0,
    this.nombreCotisationsEnRetard = 0,
    this.tauxEngagement,
    this.nombreComptesEpargne = 0,
    required this.dateCalcul,
  });

  factory CompteAdherentModel.fromJson(Map<String, dynamic> json) {
    return CompteAdherentModel(
      numeroMembre: json['numeroMembre'] as String? ?? 'N/A',
      nomComplet: json['nomComplet'] as String? ?? '',
      organisationNom: json['organisationNom'] as String?,
      dateAdhesion: json['dateAdhesion'] as String?,
      statutCompte: json['statutCompte'] as String? ?? 'ACTIF',
      soldeCotisations: _toDouble(json['soldeCotisations']),
      soldeEpargne: _toDouble(json['soldeEpargne']),
      soldeBloque: _toDouble(json['soldeBloque']),
      soldeTotalDisponible: _toDouble(json['soldeTotalDisponible']),
      encoursCreditTotal: _toDouble(json['encoursCreditTotal']),
      capaciteEmprunt: _toDouble(json['capaciteEmprunt']),
      nombreCotisationsPayees: (json['nombreCotisationsPayees'] as num?)?.toInt() ?? 0,
      nombreCotisationsTotal: (json['nombreCotisationsTotal'] as num?)?.toInt() ?? 0,
      nombreCotisationsEnRetard: (json['nombreCotisationsEnRetard'] as num?)?.toInt() ?? 0,
      tauxEngagement: (json['tauxEngagement'] as num?)?.toInt(),
      nombreComptesEpargne: (json['nombreComptesEpargne'] as num?)?.toInt() ?? 0,
      dateCalcul: json['dateCalcul'] as String? ?? '',
    );
  }

  static double _toDouble(dynamic v) {
    if (v == null) return 0;
    if (v is num) return v.toDouble();
    if (v is String) return double.tryParse(v) ?? 0;
    return 0;
  }
}
