(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}}),
         (u:user {uuid:{by}}),
         (t:instance {uuid:{target}})
   CREATE
         (l:link {uuid:{uuid}})-[:created_by]->(u)
     SET l.created_at = {created_at},
         l.name = {name}
   CREATE
         (i)<-[:link_from]-(l)-[:link_to]->(t)")
(defn create! [link]
  (let [tuples (map (fn [target-uuid]
                      [create
                       {:from (:from link)
                        :by (:by link)
                        :target target-uuid
                        :uuid (neo4j/uuid)
                        :created_at (neo4j/now-str)
                        :name (:name link)}])
                    (:to link))]
    (apply neo4j/exec-queries! tuples)))

(neo4j/defquery delete
  "MATCH (l:link {uuid:{uuid}}),
         (l)-[r]-()
   DELETE r, l")
(defn delete! [uuid]
  (neo4j/exec-query! delete
                     {:uuid uuid}))
