/// Modèle d'une transaction épargne (aligné API TransactionEpargneResponse).
class TransactionEpargneModel {
  final String? id;
  final String? compteId;
  final String? type; // DEPOT, RETRAIT, TRANSFERT_ENTRANT, TRANSFERT_SORTANT
  final double montant;
  final double soldeAvant;
  final double soldeApres;
  final String? motif;
  final DateTime? dateTransaction;
  final String? statutExecution; // REUSSIE, etc.
  final String? origineFonds;

  const TransactionEpargneModel({
    this.id,
    this.compteId,
    this.type,
    this.montant = 0,
    this.soldeAvant = 0,
    this.soldeApres = 0,
    this.motif,
    this.dateTransaction,
    this.statutExecution,
    this.origineFonds,
  });

  factory TransactionEpargneModel.fromJson(Map<String, dynamic> json) {
    return TransactionEpargneModel(
      id: json['id']?.toString(),
      compteId: json['compteId']?.toString(),
      type: json['type']?.toString(),
      montant: _toDouble(json['montant']),
      soldeAvant: _toDouble(json['soldeAvant']),
      soldeApres: _toDouble(json['soldeApres']),
      motif: json['motif'] as String?,
      dateTransaction: json['dateTransaction'] != null
          ? DateTime.tryParse(json['dateTransaction'].toString())
          : null,
      statutExecution: json['statutExecution']?.toString(),
      origineFonds: json['origineFonds'] 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;
  }

  bool get isCredit =>
      type == 'DEPOT' || type == 'TRANSFERT_ENTRANT';
  bool get isDebit =>
      type == 'RETRAIT' || type == 'TRANSFERT_SORTANT';
}
