(ns auto-ap.session-version
  (:require [bidi.bidi :as bidi]
            [auto-ap.logging :as alog]))

;; TODO this should only be done until SSR is complete
;; once it is, it should just use redirects based on headers
;; no header=use default, mismatch header=redirect to login
(def current-session-version 2)
(defn wrap-session-version
  [handler]
  (fn [request]
    (let [session  (:session request)
          route (bidi/match-route @(resolve 'auto-ap.handler/all-routes)
                                  (:uri request)
                                  :request-method (:request-method request))
          is-normal-route? (or (keyword? route)
                               (keyword? (:handler route)))] ;; TODO SSR icky
      (if (and (not= (:version session current-session-version) current-session-version)

               is-normal-route?)
        (cond
          (or (= :graphql (:handler route))
              (= :graphql route))
          {:status 401}

          (get (:headers request) "hx-request")
          {:session nil
           :status  200
           :headers {"hx-redirect" "/login"}}
          :else
          {:session nil
           :status  302
           :headers {"Location" "/login"}})
        (handler request)))))