 (defn request-headers
   "Create a set of request headers to use for interaction with the Keycloak
    REST API. This allows us to reuse the same token for multiple requests."
-  ([{:keys [openid-config credentials cm]}]
+  ([{:keys [openid-config credentials connection-manager]}]
    (let [params (merge {:grant_type "client_credentials"}
                        credentials)
          resp (client/post (get openid-config "token_endpoint")


(defn- lookup-user-id
  "Lookup email -> Keycloak user-id, via cached Keycloak API."
  [cm req-opts api-root user-id-cache email]
  (if-some [user-id (get-user-id user-id-cache email)]
    user-id
    (let [url (format "%s/users/?email=%s" api-root email)]
      (let [users (-> (client/get url (assoc req-opts :connection-manager cm)) :body json/decode)]
        (when-some [user-id (active-user users email)]
          (-> user-id-cache
              (swap! assoc email user-id)

  (log/info "Starting keycloak")
  (let [{:keys [issuer openid-config api-root] :as this} (init-keycloak (assoc data :credentials credentials :max-user-ids-cache max-user-ids-cache))
        http-timeout 10000
        connection-manager (http.conn-mgr/make-reusable-conn-manager {:timeout 2 :threads 3 :insecure? false :default-per-route 10})
        openid-config (fetch-openid-configuration issuer {:timeout http-timeout :connection-manager connection-manager})]
    (log/info "Successfully got openid-config from provider.")
    (assoc this
           :connection-manager connection-manager
           :http-timeout http-timeout
           :openid-config openid-config)))

(defmethod ig/halt-key! :akvo.lumen.component.keycloak/keycloak  [_ opts]
  (log/info :keycloak "closing connection manager" (:connection-manager opts))
  (http.conn-mgr/shutdown-manager (:connection-manager opts)))


(s/def ::client_id string?)
