 
 ;;;; Write model
 
-(defn- write-model [events]
-  (reduce update-congregation nil events))
+(defn- write-model [command events]
+  (let [state (reduce projection nil events)]
+    (get-in state [::congregations (:congregation/id command)])))
 
 
 ;;;; Command handlers

        :congregation/name new-name}])))

(defn handle-command [command events injections]
  (command-handler command (write-model events) injections))


;;;; User access


;;;; Read model

(defmulti projection (fn [_state event]
                       (:event/type event)))

(defmethod projection :default [state _event]
  state)

(defn- update-cong [state event f]
  (update-in state [::congregations (:congregation/id event)] f))

(defmethod projection :congregation.event/congregation-created
  [state event]
  (-> state
      (update-cong event (fn [congregation]
                           (-> congregation
                               (assoc :congregation/id (:congregation/id event))
                               (assoc :congregation/name (:congregation/name event))
                               (assoc :congregation/schema-name (:congregation/schema-name event)))))))

(defmethod projection :congregation.event/congregation-renamed
  [state event]
  (-> state
      (update-cong event (fn [congregation]
                           (-> congregation
                               (assoc :congregation/name (:congregation/name event)))))))

(defmethod projection :congregation.event/permission-granted
  [state event]
  (-> state
      (update-cong event (fn [congregation]
                           (-> congregation
                               (update-in [:congregation/user-permissions (:user/id event)]
                                          conj-set (:permission/id event)))))
      (permissions/grant (:user/id event) [(:permission/id event)
                                           (:congregation/id event)])))

(defmethod projection :congregation.event/permission-revoked
  [state event]
  (-> state
      (update-cong event (fn [congregation]
                           (-> congregation
                               ;; TODO: remove user when no more permissions remain
                               (update-in [:congregation/user-permissions (:user/id event)]
                                          disj (:permission/id event)))))
      (permissions/revoke (:user/id event) [(:permission/id event)
                                            (:congregation/id event)])))

(defn sudo [state user-id]
  (-> state
