(ns wanijo.link.db
  (:require [clojure.spec.alpha :as spec]
            [wanijo.specs :as specs]
            [wanijo.infrastructure.neo4j :as neo4j]))

(spec/def ::link
  (spec/keys :req-un [::neo4j/uuid
                      ::specs/created_at
                      ::name]))

(neo4j/defquery create
  "MATCH (i:instance {uuid:{from}}),
         (t:instance {uuid:{target}})
   CREATE (i)-[l:link]->(t)
      SET l.created_at = {created_at},
          l.name = {name},
          l.created_by = {by},
          l.uuid = {uuid}")
(defn create! [{:keys [from name to by]}]
  (let [tuples (map (fn [target-uuid]
                      [create
                       {:from from
                        :by by
                        :target target-uuid
                        :uuid (neo4j/uuid)
                        :created_at (neo4j/now-str)
                        :name name}])
                    to)]
    (apply neo4j/exec-queries! tuples)))

(neo4j/defquery delete
  "MATCH (:instance)-[l:link]-(:instance)
   WHERE l.uuid = {uuid}
   DELETE l")
(defn delete! [uuid]
  (neo4j/exec-query! delete
                     {:uuid uuid}))
