(ns auto-ap.routes.utils
  (:require
   [auto-ap.graphql.utils :refer [is-admin?]]
   [buddy.auth :refer [authenticated?]]
   [auto-ap.logging :as alog]
   [cemerick.url :as url]))

(defn wrap-secure [handler]
  (fn [request]
    (if (authenticated? request)
      (handler request)
      {:status 302
       :headers {"Location" "/login" }})))

(defn wrap-admin [handler]
  (fn [request]
    (if (is-admin? (:identity request))
      (handler request)
      (do 
        (alog/warn ::unauthenticated)
        {:status  302
         :headers {"Location" "/login"}}))))

(defn wrap-client-redirect-unauthenticated [handler]
  (fn [request]
    (let [response (handler request)]
      (if (= 401 (get response :status))
        (assoc-in response [:headers "hx-redirect"] "/login/")
        response))))
