class UserModel {
  const UserModel({
    required this.id,
    required this.name,
    this.username,
    this.fullName,
    this.phone,
    this.roleId,
    this.roleName,
    this.avatarUrl,
    this.isAdmin,
    this.accountType,
  });

  final int id;
  final String name;
  final String? username;
  final String? fullName;
  final String? phone;
  final int? roleId;
  final String? roleName;
  final String? avatarUrl;
  final bool? isAdmin;
  final String? accountType;

  bool get isAdminUser => (isAdmin == true) || (accountType?.toLowerCase() == 'admin');

  factory UserModel.fromJson(Map<String, dynamic> json) {
    final employee = json['employee'];
    final employeeMap = employee is Map<String, dynamic> ? employee : null;

    return UserModel(
      id: (json['id'] as num).toInt(),
      name: (json['name'] as String?)?.trim().isNotEmpty == true ? (json['name'] as String) : '—',
      username: json['username'] as String?,
      fullName: employeeMap?['full_name'] as String?,
      phone: employeeMap?['phone'] as String?,
      roleId: (employeeMap?['role_id'] as num?)?.toInt(),
      roleName: employeeMap?['role_name'] as String?,
      avatarUrl: (employeeMap?['avatar_url'] as String?) ?? (json['avatar_url'] as String?),
      isAdmin: json['is_admin'] == true,
      accountType: json['account_type'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'username': username,
      'is_admin': isAdmin,
      'account_type': accountType,
      'employee': {
        'full_name': fullName,
        'phone': phone,
        'role_id': roleId,
        'role_name': roleName,
        'avatar_url': avatarUrl,
      },
    };
  }
}
