class AppUser {
  final String id;
  final String email;
  final String role;
  final DateTime createdAt;
  final DateTime updatedAt;
  final bool changementMdpObligatoire;
  final String? nom;
  final String? prenom;
  final String? statut;
  final String? telephone;
  final String? photoUrl;
  final String? adresse;
  final String? ville;
  final String? codePostal;
  final String? relaisId;
  final String? relaisNom;

  AppUser({
    required this.id,
    required this.email,
    required this.role,
    required this.createdAt,
    required this.updatedAt,
    this.changementMdpObligatoire = false,
    this.nom,
    this.prenom,
    this.statut,
    this.telephone,
    this.photoUrl,
    this.adresse,
    this.ville,
    this.codePostal,
    this.relaisId,
    this.relaisNom,
  });

  factory AppUser.fromJson(Map<String, dynamic> json) {
    final relaisJson = json['relais'];
    final relaisMap =
        relaisJson is Map<String, dynamic> ? relaisJson : <String, dynamic>{};

    return AppUser(
      id: (json['id'] as String?) ?? '',
      email: (json['email'] as String?) ?? '',
      role: (json['role'] as String?) ?? '',
      createdAt: json['cree_le'] != null
          ? DateTime.parse(json['cree_le'] as String)
          : (json['createdAt'] != null
              ? DateTime.parse(json['createdAt'] as String)
              : DateTime.now()),
      updatedAt: json['modifie_le'] != null
          ? DateTime.parse(json['modifie_le'] as String)
          : (json['updatedAt'] != null
              ? DateTime.parse(json['updatedAt'] as String)
              : DateTime.now()),
      changementMdpObligatoire:
          json['changement_mdp_obligatoire'] as bool? ?? false,
      nom: json['nom'] as String?,
      prenom: json['prenom'] as String?,
      statut: json['statut'] as String?,
      telephone: json['telephone'] as String?,
      photoUrl: json['photo_url'] as String?,
      adresse: json['adresse'] as String?,
      ville: json['ville'] as String?,
      codePostal: json['code_postal'] as String?,
      relaisId: (json['relaisId'] ?? json['relais_id'] ?? relaisMap['id'])
          ?.toString(),
      relaisNom: relaisMap['nom']?.toString(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'email': email,
      'role': role,
      'createdAt': createdAt.toIso8601String(),
      'updatedAt': updatedAt.toIso8601String(),
      'changement_mdp_obligatoire': changementMdpObligatoire,
      'nom': nom,
      'prenom': prenom,
      'statut': statut,
      'telephone': telephone,
      'photo_url': photoUrl,
      'adresse': adresse,
      'ville': ville,
      'code_postal': codePostal,
      'relais_id': relaisId,
      'relais_nom': relaisNom,
    };
  }

  String get fullName => '${prenom ?? ''} ${nom ?? ''}'.trim();
}
