public async Task <ThreadWithMessagesResponseModel> AddNewMessageAsync(NewMessageRequestModel newMessage) { DateTime? readAt; LogEntity logEntity = new LogEntity(); var newMessageEntity = _mapper.Map <NewMessageRequestModel, MessageEntity>(newMessage); var thread = await _threadRepository.GetAsync(newMessageEntity.ThreadId); if (thread == null) { throw new InvalidRequestException(); } thread.ArchivedBy = new List <int>(); await _threadRepository.UpdateAsync(thread); newMessageEntity.ReadBy.Add(newMessage.FromUserId); if (newMessageEntity.ReadBy.Count > 0) { readAt = DateTime.UtcNow; } else { readAt = null; } newMessageEntity.IsImportant = newMessage.IsImportant; newMessageEntity.FromUserName = newMessage.FromUserName; // Add message and Get all messages var messages = _mapper.Map <IEnumerable <MessageEntity>, IEnumerable <MessageResponseModel> >(await _messageRepository.AddAndGetAsync(newMessageEntity)).ToList(); // update thread modified time thread.ModifiedAt = DateTime.UtcNow; await _threadRepository.UpdateAsync(thread); var participantsDetails = _mapper.Map <IEnumerable <ChatUser>, IEnumerable <UserContactResponseModel> >(await _contactRepository.GetChatUserDetailsAsync(thread.Participants)); var threadWithMessages = _mapper.Map(messages, _mapper.Map <ThreadEntity, ThreadWithMessagesResponseModel>(thread, options => options.Items[MappingConstants.ThreadRequestUserId] = newMessage.FromUserId)); await LogMessage(thread, messages.OrderByDescending(x => x.CreatedAt).First(), readAt); return(_mapper.Map(participantsDetails, threadWithMessages)); }