(ns auto-ap.routes.events
  (:require [auto-ap.routes.utils :refer [wrap-secure]]
            [auto-ap.yodlee.import :as yodlee-import]
            [config.core :refer [env]]
            [clj-http.client :as http]
            [clj-time.coerce :as c]
            [clj-time.core :as time]
            [clj-time.periodic :as p]
            [clj-time.predicates :as pred]
            [clojure.data.json :as json]
            [compojure.core :refer [GET PUT POST context defroutes
                                    wrap-routes]])
  (:import (org.joda.time DateTime)))

(defroutes routes
  (context "/events" []
           
           (POST "/yodlee-import" {:keys [query-params headers body] :as x}
                 (let [notification-type (get headers "x-amz-sns-message-type")]
                   (println "Received notification " notification-type)
                   (if (= "SubscriptionConfirmation" notification-type)
                     (do
                       (println "Responding to confirmation" )
                       (let [json (json/read-str (slurp body))]
                         (println json)
                         (http/get (get json "SubscribeURL"))))
                     (do
                       (println "importing from yodlee")
                       (yodlee-import/do-import))))
                 
                 {:status 200
                  :body "{}"
                  :headers {"Content-Type" "application/edn"}})))
