(ns auto-ap.plaid.core
  (:require
   [clj-http.client :as client]
   [clojure.data.json :as json]
   [clojure.tools.logging :as log]
   [config.core :as cfg :refer [env]]
   [auto-ap.time :as atime]))

(def base-url (-> env :plaid :base-url))

(def client-id (-> env :plaid :client-id))
(def secret-key (-> env :plaid :secret-key))


(defn get-link-token [client-code]
  (-> (client/post (str base-url "/link/token/create") 
                   {:as :json
                    :headers {"Content-Type" "application/json"}
                    :body (json/write-str {"client_id" client-id
                                           "secret" secret-key
                                           "client_name" "Integreat Consulting"
                                           "country_codes" ["US"]
                                           "language" "en"
                                           "user" {"client_user_id" client-code}
                                           "products" ["transactions"]})})
      :body
      :link_token))

(defn exchange-public-token [public-token _]
  (-> (client/post (str base-url "/item/public_token/exchange") 
                   {:as :json
                    :headers {"Content-Type" "application/json"}
                    :body (json/write-str {"client_id" client-id
                                           "secret" secret-key
                                           "public_token" public-token})})
      :body
      (doto println)))

(defn get-accounts [access-token ]
  (-> (client/post (str base-url "/accounts/get") 
                   {:as :json
                    :headers {"Content-Type" "application/json"}
                    :body (json/write-str {"client_id" client-id
                                           "secret" secret-key
                                           "access_token" access-token})})
      :body))

(defn get-transactions [access-token account-id start end]
  (log/infof "looking up transactions from %s to %s for %s" start end account-id)
  (-> (client/post (str base-url "/transactions/get") 
                   {:as :json
                    :headers {"Content-Type" "application/json"}
                    :body (json/write-str {"client_id" client-id
                                           "secret" secret-key
                                           "access_token" access-token
                                           "start_date" (atime/unparse start atime/iso-date)
                                           "end_date" (atime/unparse end atime/iso-date)
                                           "options" {"account_ids" [account-id]}})})
      :body))

