 ;;; KeycloakAgent Component
 ;;;
 
-(defrecord KeycloakAgent [issuer openid-config api-root]
+(defrecord KeycloakAgent [issuer openid-config api-root user-id-cache]
   p/KeycloakUserManagement
   (add-user-with-email [{:keys [api-root] :as keycloak} tenant-label email]
     (let [request-headers (request-headers keycloak)

          (println (format "Tried to remove user: %s" user-id))
          (lib/internal-server-error))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; WIP
;;;

(defn- api-get
  [headers url]
  (-> url
      (client/get {:headers headers})
      :body
      json/decode))

(defn allowed-paths
  "From email get Keycloak user and returns the set of allowed paths for email"
  [{:keys [api-root] :as keycloak} email]
  (let [request-headers (request-headers keycloak)
        users (api-get request-headers
                       (format "%s/users/?email=%s" api-root email))
        validated-user-id (-> (filter #(and (= (get % "email") email)
                                            (get % "emailVerified"))
                                      users)
                              first
                              (get "id"))
        user-groups (api-get request-headers
                             (format "%s/users/%s/groups" api-root
                                     validated-user-id))]
    (reduce (fn [paths {:strs [path]}]
              (conj paths (subs path 12))) ;; remove leading /akvo/lumen/
            #{} user-groups)))



(defn- keycloak [{:keys [credentials url realm]}]
  (map->KeycloakAgent {:api-root (format "%s/admin/realms/%s" url realm)
                       :credentials credentials
                       :issuer (format "%s/realms/%s" url realm)
                       :user-id-cache (atom {})}))

(defmethod ig/init-key :akvo.lumen.component.keycloak/data  [_ {:keys [url realm] :as opts}]
  (try
