(ns auto-ap.handler
  (:require [amazonica.core :refer [defcredential]]
            [auto-ap.routes.auth :as auth]
            [auto-ap.routes.events :as events]
            [auto-ap.routes.exports :as exports]
            [auto-ap.routes.queries :as queries]
            [auto-ap.routes.graphql :as graphql]
            [auto-ap.routes.invoices :as invoices]
            [auto-ap.routes.yodlee :as yodlee]
            [auto-ap.routes.yodlee2 :as yodlee2]
            [buddy.auth.backends.token :refer [jws-backend]]
            [buddy.auth.middleware :refer [wrap-authentication wrap-authorization]]
            [clojure.tools.logging :as log]
            [clojure.string :as str]
            [compojure.core :refer :all]
            [compojure.route :as route]
            [config.core :refer [env]]
            [mount.core :as mount]
            [ring.middleware.edn :refer [wrap-edn-params]]
            [ring.middleware.gzip :refer [wrap-gzip]]
            [ring.middleware.multipart-params :as mp]
            [ring.middleware.params :refer [wrap-params]]
            [ring.middleware.reload :refer [wrap-reload]]
            [ring.util.response :as response]
            [unilog.context :as lc]
            [auto-ap.client-routes :as client-routes]
            [bidi.bidi :as bidi]))

(when (:aws-access-key-id env) 
  (defcredential (:aws-access-key-id env) (:aws-secret-access-key env) (:aws-region env)))

(def running? (atom false))

(mount/defstate manage-running?
  :start (reset! running? true)
  :stop (reset! running? false))

(defroutes static-routes
  (GET "/"  [] (response/resource-response "index.html" {:root "public"})) 
  (route/resources "/")
  (routes (ANY "*" {:keys [path]  :as r}
               (if (bidi/match-route client-routes/routes (:uri r))
                 (response/resource-response "index.html" {:root "public"})
                 {:status 404
                  :body "Not found"}))))

(defroutes health-check
  (GET "/health-check"  []
       (if @running?
         {:status 200
          :body "Ok"}
         {:status 503
          :body "Application shut down"})))

(defroutes api-routes
  (context "/api" []
           exports/export-routes
           yodlee/routes
           yodlee2/routes
           queries/query2-routes
           invoices/routes
           graphql/routes
           auth/routes
           health-check))


(def auth-backend (jws-backend {:secret (:jwt-secret env) :options {:alg :hs512}}))

(defn wrap-transaction [handler]
  (fn [request]
    (handler request)))

(def app-routes
  (routes 
   (wrap-transaction api-routes)
   static-routes))

(defn wrap-logging [handler]
  (fn [request]
    (lc/with-context {:uri (:uri request)
                      :source "request"
                      :user-role (:user/role (:identity request))
                      :user-name (:user/name (:identity request))}

      (when-not (str/includes? (:uri request) "health-check")
        (log/info "Beginning request" (:uri request)))
      (handler request))))



(def app
  (->  #'app-routes
       (wrap-logging)
      (wrap-authorization auth-backend)
      (wrap-authentication auth-backend)
      (wrap-reload)
      (wrap-params)
      (mp/wrap-multipart-params)
      (wrap-edn-params)
      #_(wrap-gzip)))
