ChatSummary.fromMap constructor

ChatSummary.fromMap(
  1. Map<String, dynamic> map,
  2. String currentUserId
)

Factory constructor to create a ChatSummary from Firestore data. The currentUserId is used to determine the other user's ID in the chat.

Implementation

factory ChatSummary.fromMap(Map<String, dynamic> map, String currentUserId) {
  try {
    return ChatSummary(
      chatId: map['chatId'] ?? "",
      lastMessage: map['lastMessage'] ?? "No message",
      lastMessageSenderId: map['lastMessageSender'] ?? "Unknown",
      lastMessageType: MessageType.values.any((e) =>
              e.toString().split('.').last ==
              (map['lastMessageType'] ?? "text"))
          ? MessageType.values.firstWhere(
              (e) =>
                  e.toString().split('.').last ==
                  (map['lastMessageType'] ?? "text"),
            )
          : MessageType.text,
      lastMessageTime:
          (map['lastMessageTime'] as Timestamp?)?.toDate() ?? DateTime.now(),
      users: List<String>.from(map['users'] ?? []),
      otherUserId: (map['users'] is List && (map['users'] as List).isNotEmpty)
          ? (map['users'] as List<dynamic>)
              .map((e) => e.toString())
              .firstWhere((id) => id != currentUserId,
                  orElse: () => "Unknown")
          : "Unknown",
      unreadMessageCount: Map<String, int>.from(map['unreadMessageCount'] ??
          {}), // 🔥 Fetch unread count from Firestore
    );
  } catch (e) {
    e.log("❌ Error converting Firestore data to ChatSummary");
    return ChatSummary(
      chatId: "",
      lastMessage: "Error loading message",
      lastMessageType: MessageType.text,
      lastMessageTime: DateTime.now(),
      users: [],
      otherUserId: "Unknown",
      lastMessageSenderId: 'Unknown',
      unreadMessageCount: {}, // 🔥 Default unread count to 0
    );
  }
}