Edit

$ctxMongo->upsert('ai_chat_sessions',
                ['session_id' => $chatSessionId],
                [
                    'session_id' => $chatSessionId,
                    'created_at' => $existingSession['created_at'] ?? date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                    'title' => $sessionTitle,
                    'agent' => $chatAgent ?? $chatMode,
                    'provider' => $chatProvider,
                    'model' => $usedModel,
                    'context_thread_ids' => $resolvedThreadIds,
                    'contact_id' => $chatContactId ?: null,
                    'contact_name' => $ctxContact['name'] ?? null,
                    'messages' => $sessionMessages,
                ]
            );

$ctxMongo->insertOrUpdate('ai_chat_sessions', [
                    'session_id' => $chatSessionId,
                    'created_at' => $existingSession['created_at'] ?? date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                    'title' => $sessionTitle,
                    'agent' => $chatAgent ?? $chatMode,
                    'provider' => $chatProvider,
                    'model' => $usedModel,
                    'context_thread_ids' => $resolvedThreadIds,
                    'contact_id' => $chatContactId ?: null,
                    'contact_name' => $ctxContact['name'] ?? null,
                    'messages' => $sessionMessages,
                ], ['session_id']);