From d956b887d668970eb8f4b592af4786fb6349f424 Mon Sep 17 00:00:00 2001
From: Bruno Muniz Azevedo Filho <bruno@elixxir.io>
Date: Sun, 26 Jun 2022 23:15:08 -0300
Subject: [PATCH] Working on groups issue

---
 .../Session/Session+Contacts.swift            | 25 ++++++++++++++++++-
 Sources/Integration/Session/Session.swift     | 10 +++++---
 2 files changed, 30 insertions(+), 5 deletions(-)

diff --git a/Sources/Integration/Session/Session+Contacts.swift b/Sources/Integration/Session/Session+Contacts.swift
index 08787e2c..4994cc2d 100644
--- a/Sources/Integration/Session/Session+Contacts.swift
+++ b/Sources/Integration/Session/Session+Contacts.swift
@@ -200,6 +200,29 @@ extension Session {
         }
 
         try client.bindings.removeContact(contact.marshaled!)
-        try dbManager.deleteContact(contact)
+
+        /// Currently this cascades into deleting
+        /// all messages w/ contact.id == senderId
+        /// But this shouldn't be the always the case
+        /// because if we have a group / this contact
+        /// the messages will be gone as well.
+        ///
+        /// Suggestion: If there's a group where this user belongs to
+        /// we will just cleanup the contact model stored on the db
+        /// leaving only username and id which are the equivalent to
+        /// .stranger contacts.
+        ///
+        //try dbManager.deleteContact(contact)
+
+        _ = try? dbManager.deleteMessages(Message.Query(chat: .direct(myId, contact.id)))
+        var contact = contact
+        contact.email = nil
+        contact.phone = nil
+        contact.photo = nil
+        contact.isRecent = false
+        contact.marshaled = nil
+        contact.authStatus = .stranger
+        contact.nickname = contact.username
+        _ = try? dbManager.saveContact(contact)
     }
 }
diff --git a/Sources/Integration/Session/Session.swift b/Sources/Integration/Session/Session.swift
index 7d8d2088..8758ff86 100644
--- a/Sources/Integration/Session/Session.swift
+++ b/Sources/Integration/Session/Session.swift
@@ -305,9 +305,11 @@ public final class Session: SessionType {
 
     private func setupBindings() {
         client.requests
-            .sink { [unowned self] in
-                if let _ = try? dbManager.fetchContacts(.init(id: [$0.id])).first {
-                    return
+            .sink { [unowned self] contact in
+                let query = Contact.Query(id: [contact.id])
+
+                if let prexistent = try? dbManager.fetchContacts(query).first {
+                    guard prexistent.authStatus == .stranger else { return }
                 }
 
                 if self.inappnotifications {
@@ -315,7 +317,7 @@ public final class Session: SessionType {
                     DeviceFeedback.shake(.notification)
                 }
 
-                verify(contact: $0)
+                verify(contact: contact)
             }.store(in: &cancellables)
 
         client.requestsSent
-- 
GitLab