(ns auto-ap.import.common
  (:require
   [auto-ap.datomic :refer [conn pull-ref random-tempid]]
   [auto-ap.logging :as alog]
   [datomic.api :as dc]))

(defn bank-account->integration-id [bank-account]
  (or (pull-ref (dc/db conn) :bank-account/integration-status bank-account)
      (random-tempid)))

(defn wrap-integration [f bank-account]
  (try 
    (let [result (f)]
      @(dc/transact-async conn [{:db/id bank-account
                          :bank-account/integration-status
                          {:db/id                           (bank-account->integration-id bank-account)
                           :integration-status/state        :integration-state/success
                           :integration-status/last-attempt (java.util.Date.)
                           :integration-status/last-updated (java.util.Date.)}}])
      result)
    (catch Exception e
      @(dc/transact-async conn [{:db/id bank-account
                          :bank-account/integration-status
                          {:db/id                           (bank-account->integration-id bank-account)
                           :integration-status/state        :integration-state/failed
                           :integration-status/last-attempt (java.util.Date.)
                           :integration-status/message      (.getMessage e)}}])
      (alog/warn ::integration-failed :error e)
      nil)))
