enum UserRole { admin, member }

extension UserRoleExtension on UserRole {
  String get label {
    switch (this) {
      case UserRole.admin:
        return 'ادمین';
      case UserRole.member:
        return 'کاربر';
    }
  }

  String get apiValue => name;
}

class UserModel {
  final String id;
  final String username;
  final String? phoneNumber;
  final UserRole role;
  final bool isActive;
  final DateTime? createdAt;

  /// Only available immediately after creation or secret reset
  final String? secret;

  const UserModel({
    required this.id,
    required this.username,
    this.phoneNumber,
    required this.role,
    required this.isActive,
    this.createdAt,
    this.secret,
  });

  factory UserModel.fromJson(Map<String, dynamic> json) {
    // Backend only exposes is_admin (no role field)
    UserRole mappedRole = json['is_admin'] == true
        ? UserRole.admin
        : UserRole.member;

    return UserModel(
      id: json['id'].toString(),
      username: json['username'] as String,
      phoneNumber: json['phone_number'] as String?,
      role: mappedRole,
      isActive: (json['is_active'] as bool?) ?? true,
      createdAt: json['created_at'] != null
          ? DateTime.tryParse(json['created_at'] as String)
          : null,
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'username': username,
        'phone_number': phoneNumber,
        'is_admin': role == UserRole.admin,
        'is_active': isActive,
        if (createdAt != null) 'created_at': createdAt!.toIso8601String(),
      };

  UserModel copyWith({
    String? id,
    String? username,
    String? phoneNumber,
    UserRole? role,
    bool? isActive,
    DateTime? createdAt,
    String? secret,
  }) {
    return UserModel(
      id: id ?? this.id,
      username: username ?? this.username,
      phoneNumber: phoneNumber ?? this.phoneNumber,
      role: role ?? this.role,
      isActive: isActive ?? this.isActive,
      createdAt: createdAt ?? this.createdAt,
      secret: secret ?? this.secret,
    );
  }
}
