(ns auto-ap.ssr.common-handlers
  (:require [auto-ap.ssr.form-cursor :as fc]
            [auto-ap.ssr.utils :refer [html-response wrap-schema-enforce]]))


(defn add-new-entity-handler
  ([path render-fn] (add-new-entity-handler path
                                            render-fn
                                            (fn default-data [base _]   
                                              base)))
  ([path render-fn build-data]
   (-> (fn new-entity [{{:keys [index]} :query-params :as request}]
         (html-response
          (fc/start-form-with-prefix (conj path (or index 0))
                                     (build-data {:db/id (str (java.util.UUID/randomUUID))
                                                         :new?  true} request)
                                     []
                                     (render-fn fc/*current* request))))
       (wrap-schema-enforce :query-schema [:map
                                           [:index {:optional true
                                                    :default  0} [nat-int? {:default 0}]]]))))

(defn add-new-primitive-handler [path default-value render-fn]
  (-> (fn new-location-match [{{:keys [index]} :query-params}]
        (html-response
         (fc/start-form-with-prefix (conj path (or index 0))
                                    default-value
                                    []
                                    (render-fn fc/*current*))))
      (wrap-schema-enforce :query-schema [:map
                                          [:index {:optional true
                                                   :default  0} [nat-int? {:default 0}]]])))