(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]
    #_(println "AUTHENTICATE" (authenticated? request))
    (cond (authenticated? request)
          (handler request)

          (get (:headers request) "hx-request")
          {:status 401
           :headers {"hx-redirect" (str "/login?"
                                        (url/map->query {"redirect-to" (:uri request)}))}}

          :else
          {:status 302
           :headers {"Location" (str "/login?"
                                     (url/map->query {"redirect-to" (:uri request)}))}})))

(defn wrap-admin [handler]
  (fn [request]
    #_(println "ADMIN " (is-admin? (:identity request)) (:identity request))
    (if (is-admin? (:identity request))
      (handler request)
      (do
        (alog/warn ::unauthenticated)
        {:status  302
         :headers {"Location" (str "/login?"
                                   (url/map->query {"redirect-to" (:uri request)}))}}))))

(defn wrap-client-redirect-unauthenticated [handler]
  (fn [request]
    (let [response (handler request)]
      #_(println "HEREEEEE"  (get response :status))
      (if (= 401 (get response :status))
        (-> response
            (assoc-in [:headers "hx-redirect"] (str "/login?"
                                                    (url/map->query {"redirect-to" (:uri request)}))))
        response))))
