/// Modèle d'un compte épargne (aligné API CompteEpargneResponse).
class CompteEpargneModel {
  final String? id;
  final String? membreId;
  final String? organisationId;
  final String? numeroCompte;
  final String? typeCompte;
  final double soldeActuel;
  final double soldeBloque;
  final String? statut;
  final DateTime? dateOuverture;
  final DateTime? dateDerniereTransaction;
  final String? description;

  const CompteEpargneModel({
    this.id,
    this.membreId,
    this.organisationId,
    this.numeroCompte,
    this.typeCompte,
    this.soldeActuel = 0,
    this.soldeBloque = 0,
    this.statut,
    this.dateOuverture,
    this.dateDerniereTransaction,
    this.description,
  });

  factory CompteEpargneModel.fromJson(Map<String, dynamic> json) {
    return CompteEpargneModel(
      id: json['id']?.toString(),
      membreId: json['membreId']?.toString(),
      organisationId: json['organisationId']?.toString(),
      numeroCompte: json['numeroCompte'] as String?,
      typeCompte: json['typeCompte'] as String?,
      soldeActuel: _toDouble(json['soldeActuel']),
      soldeBloque: _toDouble(json['soldeBloque']),
      statut: json['statut'] as String?,
      dateOuverture: json['dateOuverture'] != null ? DateTime.tryParse(json['dateOuverture'].toString()) : null,
      dateDerniereTransaction: json['dateDerniereTransaction'] != null ? DateTime.tryParse(json['dateDerniereTransaction'].toString()) : null,
      description: json['description'] as String?,
    );
  }

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

  double get soldeDisponible => soldeActuel - soldeBloque;
}
