 
 (ns territory-bro.api
   (:require [camel-snake-kebab.core :as csk]
-            [clojure.test :refer :all]
             [clojure.tools.logging :as log]
             [compojure.core :refer [defroutes GET POST ANY]]
             [liberator.core :refer [defresource]]


(defn- fetch-congregation [conn state user-id congregation]
  (let [cong-id (:congregation/id congregation)]
    (db/use-tenant-schema conn (:congregation/schema-name congregation))
    {:id (:congregation/id congregation)
     :name (:congregation/name congregation)
     :permissions (->> (permissions/list-permissions state user-id [cong-id])
                       (map (fn [permission]
                              [permission true]))
                       (into {}))
     :territories (gis-db/get-territories conn)
     :congregation-boundaries (gis-db/get-congregation-boundaries conn)
     :subregions (gis-db/get-subregions conn)
     :card-minimap-viewports (gis-db/get-card-minimap-viewports conn)
     :users (->> (user/get-users conn {:ids (congregation/get-users state cong-id)})
                 (map (fn [user]
                        (-> (:user/attributes user)
                            (assoc :id (:user/id user))
                            (assoc :sub (:user/subject user))))))}))

(defn- fetch-congregation2 [conn state user-id congregation]
  (let [cong-id (:congregation/id congregation)]
    {:id (:congregation/id congregation)
     :name (:congregation/name congregation)
     :permissions (->> (permissions/list-permissions state user-id [cong-id])
                       (map (fn [permission]
                              [permission true]))
                       (into {}))
     :territories (vec (vals (get-in state [::territory/territories cong-id])))
     :congregation-boundaries (vec (vals (get-in state [::congregation-boundary/congregation-boundaries cong-id])))
     :subregions (vec (vals (get-in state [::subregion/subregions cong-id])))
     :card-minimap-viewports (vec (vals (get-in state [::card-minimap-viewport/card-minimap-viewports cong-id])))
     :users (->> (user/get-users conn {:ids (congregation/get-users state cong-id)})
                 (map (fn [user]
                        (-> (:user/attributes user)

            congregation (congregation/get-my-congregation state cong-id user-id)]
        (when-not congregation
          (forbidden! "No congregation access"))
        (ok (-> (fetch-congregation conn state user-id congregation)
                (format-for-api)
                (validate-congregation)))))))

