(ns auto-ap.ssr.ledger.investigate 
  (:require
   [auto-ap.permissions :refer [wrap-must]]
   [auto-ap.query-params :refer [wrap-copy-qp-pqp]]
   [auto-ap.routes.ledger :as route]
   [auto-ap.routes.utils :refer [wrap-client-redirect-unauthenticated]]
   [auto-ap.ssr.components :as com]
   [auto-ap.ssr.grid-page-helper :refer [table* wrap-apply-sort]]
   [auto-ap.ssr.grid-page-helper :as helper]
   [auto-ap.ssr.hx :as hx]
   [auto-ap.ssr.ledger.common :refer [grid-page query-schema]]
   [auto-ap.ssr.utils :refer [apply-middleware-to-all-handlers html-response
                              modal-response wrap-merge-prior-hx
                              wrap-schema-enforce]]
   [auto-ap.time :as atime]))


(def altered-grid-page 
  (assoc grid-page 
         :id "yoho"
         :raw? true 
         :check-boxes? false
         :route ::route/investigate-results))


(defn investigate [request]
  (modal-response 
   (com/modal  {:class "max-h-[600px]"}
              (com/modal-card  {:hx-vals (hx/json (cond-> (:query-params request)
                                                    true (update  :numeric-code pr-str)
                                                    (:start-date (:query-params request)) (update :start-date #(some-> (atime/unparse-local % atime/normal-date)))
                                                    (:end-date (:query-params request)) (update :end-date #(some-> (atime/unparse-local % atime/normal-date))))) }
                              [:div "Ledger entries"]
                              (table*
                               altered-grid-page
                               identity
                               request
                               #_(assoc-in request [:query-params :sort] [{:sort-key "date" :asc? false :name "Date"}]))
                              nil)
    )))

(def key->handler
  (apply-middleware-to-all-handlers
   (->
    {::route/investigate investigate 
     ::route/investigate-results (helper/table-route altered-grid-page :push-url? false)}
    )
   (fn [h]
     (-> h
         (wrap-apply-sort grid-page)
         (wrap-copy-qp-pqp)
         (wrap-merge-prior-hx)
         (wrap-schema-enforce :query-schema query-schema)
         (wrap-schema-enforce :hx-schema query-schema)
         (wrap-must {:activity :read :subject :ledger})
         (wrap-client-redirect-unauthenticated)))))


