 
 (defn access-token
   "Fetch a new access token using a refresh token"
-  [refresh-token]
-  (-> (http/post "https://kc.akvotest.org/auth/realms/akvo/protocol/openid-connect/token"
+  [token-endpoint refresh-token]
+  (-> (http/post token-endpoint
                  {:form-params {"client_id" "akvo-lumen"
                                 "refresh_token" refresh-token
                                 "grant_type" "refresh_token"}

      :refresh_token))

(defn flow-api-headers
  [refresh-token]
  {"Authorization" (format "Bearer %s" (access-token refresh-token))
   "User-Agent" "lumen"
   "Accept" "application/vnd.akvo.flow.v2+json"
   "X-Akvo-Email" "akvo.flow.user.test2@gmail.com"})

(defn survey-definition
  [api-root access-token instance survey-id]
  (-> (format "%s/orgs/%s/surveys/%s"
              api-root instance survey-id)
      (http/get {:headers (flow-api-headers access-token)
                 :as :json})
      :body))

(defn form-instances* [refresh-token url]
  (let [response (-> url
                     (http/get {:headers (flow-api-headers refresh-token)
                                :as :json-string-keys})
                     :body)]
    (lazy-cat (get response "formInstances")
              (when-let [url (get response "cursor")]
                (form-instances* refresh-token url)))))

(defn form-instances
  "Returns a lazy sequence of form instances"
  [refresh-token form]
  (let [initial-url (str (:formInstancesUrl form) "?pageSize=300")]
    (form-instances* refresh-token initial-url)))

(defn data-points*
  [access-token url]
  (-> url
      (http/get {:headers (flow-api-headers access-token)
                 :as :json-string-keys})
      :body))

(defn data-points
  "Returns all survey data points"
  [refresh-token survey]
  (loop [all-data-points []
         response (data-points* (access-token refresh-token)
                                (str (:dataPointsUrl survey)
                                     "?pageSize=300"))]
    (if-let [url (get response "cursor")]
      (recur (into all-data-points (get response "dataPoints"))
             (data-points* (access-token refresh-token) url))
      all-data-points)))

(defn question-type->lumen-type


(defn form-data
  "Returns a lazy sequence of form data, ready to be inserted as a lumen dataset"
  [headers-fn survey form-id]
  (let [form (form survey form-id)
        data-points (index-by "id" (data-points headers-fn survey))]
    (map (fn [form-instance]
           (let [data-point-id (get form-instance "dataPointId")]
             (assoc (response-data form (get form-instance "responses"))
