 
 (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"}


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

                    "submitter" (get form-instance "submitter")
                    "submitted_at" (some-> (get form-instance "submissionDate")
                                           sql-timestamp))))
         (form-instances headers-fn form))))

(defn create-dataset [tenant-conn headers-fn table-name survey form-id]
  (let [columns (dataset-columns (form survey form-id))
        data-rows (form-data headers-fn survey form-id)]
    (jdbc/execute! tenant-conn [(create-data-table table-name columns)])
    (doseq [data (partition-all 300 data-rows)]
      (jdbc/insert-multi! tenant-conn table-name data))
    columns))

(defmethod import/make-dataset-data-table "AKVO_FLOW"
  [tenant-conn {:keys [flow-api-root keycloak-realm keycloak-url]} table-name {:strs [instance surveyId formId refreshToken]}]
  (try
    (let [token-endpoint (format "%s/realms/%s/protocol/openid-connect/token"
                                 keycloak-url
                                 keycloak-realm)
          refresh-token (offline-token token-endpoint refreshToken)
          headers-fn #(flow-api-headers token-endpoint refresh-token)]
      {:success? true
       :columns (let [survey (survey-definition flow-api-root
                                                headers-fn
                                                instance
                                                surveyId)]
                  (create-dataset tenant-conn
                                  headers-fn
                                  table-name
                                  survey
                                  formId))})
