(ns wanijo.infrastructure.auth
  (:require [compojure.core :refer [POST GET defroutes]]
            [ring.util.response :refer [redirect]]
            [ring.util.anti-forgery :refer [anti-forgery-field]]
            [buddy.hashers :as hashers]
            [hiccup.form :as hform]
            [wanijo.infrastructure.view :as view]
            [wanijo.infrastructure.routing :refer [register! path]]
            [wanijo.user.db :as user-domain]))

(defn- login-check! [req]
  (let [{{:keys [uname pw]} :params} req
        unode (user-domain/find! uname)
        pwmatch (when-let [hash (:pw unode)]
                  (hashers/check pw hash))]
    (if pwmatch
      (-> (redirect (path :home))
          (assoc-in [:session :ident] uname)
          (assoc-in [:session :uuid] (:uuid unode)))
      (assoc (redirect (path :auth-login))
             :flash :invalid-credentials))))

(defn login! [req]
  (view/layout
   :content
   [[:h1 "Login"]
    (hform/form-to
     [:post (path :auth-login-check)]
     (when (:flash req) [:section.flash (:flash req)])
     ;;
     (hform/label "uname" "Name")
     (hform/text-field {:required "required" :autofocus true} "uname")
     ;;
     (hform/label "pw" "Password")
     (hform/password-field {:required "required"} "pw")
     ;;
     (hform/submit-button "Login")
     (anti-forgery-field))]))

(defroutes routes
  (GET (register! :auth-login "/login") [] login!)
  (POST (register! :auth-login-check "/login-check") [] login-check!)
  (GET (register! :auth-logout "/logout") [] (assoc (redirect "/login")
                                                    :session nil)))
