(ns wanijo.tag.routes
  (:require [compojure.core :refer [defroutes POST DELETE]]
            [ring.util.response :as resp]
            [formulare.core :as form]
            [wanijo.infrastructure.routing :refer [register! path]]
            [wanijo.schema.db :as domain-schema]
            [wanijo.instance.db :as db-instance]
            [wanijo.instance.view.show :refer [show]]
            [wanijo.tag
             [db :as domain]
             [forms :as forms]]))

(defn create-tag! [instance-uuid req]
  (let [{new-names :newnames} (form/form-data forms/new-tag req)
        user-uuid (-> req :session :uuid)]
    (if (form/valid? forms/new-tag req)
      (do
        (domain/merge-tags! new-names
                            instance-uuid
                            user-uuid)
        (resp/redirect (path :instance-show
                             {:uuid instance-uuid})))
      (show
       (db-instance/full-instance-by-uuid! instance-uuid)
       (domain-schema/accessible-schemas! user-uuid)
       req))))

(defn remove-tag! [uuid instance-uuid]
  (domain/remove-tag! uuid instance-uuid)
  (resp/redirect (path :instance-edit-form {:uuid instance-uuid})))

(defroutes routes
  (POST (register! :tag-create "/tag/:instance-uuid")
        [instance-uuid :as req]
        (create-tag! instance-uuid req))
  (DELETE (register! :tag-remove "/tag/:uuid/:instance-uuid")
          [uuid instance-uuid]
          (remove-tag! uuid instance-uuid)))
