(ns auto-ap.routes.vendors
  (:require [auto-ap.db.vendors :as vendors]
            [auto-ap.entities.vendors :as entity]
            [auto-ap.routes.utils :refer [wrap-secure wrap-spec]]
            [auto-ap.db.reminders :as reminders]
            [clj-time.core :as time]
            [compojure.core :refer [GET POST PUT context defroutes wrap-routes]]))

(defroutes routes
  (wrap-routes
   (context "/vendors" []
            (GET "/" []
                 {:status 200
                  :body (pr-str (vendors/get-all))
                  :headers {"Content-Type" "application/edn"}})
            (wrap-routes
             (PUT "/:id" {:keys [edn-params] {:keys [id]} :route-params :as r}
                  {:status 200
                   :body (pr-str (vendors/upsert id edn-params))
                   :headers {"Content-Type" "application/edn"}})
             #(wrap-spec % ::entity/vendor))
            (POST "/:id/remind" {:keys [edn-params] {:keys [id :<< as-int]} :route-params :as r}
                  (let [id (if (int? id)
                             id
                             (Integer/parseInt id))
                        vendor (vendors/get-by-id id)]
                    (reminders/insert (assoc
                                       (reminders/template)
                                       :email (:primary-email vendor)
                                       :vendor-id id
                                       :scheduled (time/now)))
                    (-> (reminders/get-ready)
                        (reminders/send-emails))
                    {:status 200
                     :body "{}"
                     :headers {"Content-Type" "application/edn"}}))
            (wrap-routes
             (POST "/" {:keys [edn-params] :as r}
                             
                             {:status 200
                              :body (pr-str (vendors/insert edn-params))
                              :headers {"Content-Type" "application/edn"}})
             #(wrap-spec % ::entity/vendor)))
   wrap-secure))
