(ns auto-ap.ssr.utils
  (:require
   [auto-ap.logging :as alog]
   [config.core :refer [env]]
   [hiccup2.core :as hiccup]))

(defn html-response [hiccup & {:keys [status] :or {status 200}}]
  {:status  status
   :headers {"Content-Type" "text/html"}
   :body    (str
              (hiccup/html 
                {}
                hiccup))})

(defn wrap-error-response [handler]
  (fn  [request]
    (try
      (handler request)
      (catch Exception e
        (if-let [v (or (:validation-error (ex-data e))
                       (:validation-error (ex-data (.getCause e))))]
          
          (do 
            (alog/warn ::request-validation-error
                       :exception e)
            (html-response
              [:div.notification.is-warning.is-light
               v]
              :status 400))
          (do 
            (alog/error ::request-error
                        :exception e)
            (when (= "dev" (:dd-env env))
              (println e))
            (html-response
              [:div.notification.is-danger.is-light
               "Server error occured."
               (ex-message e)]
              :status 500)))))))

