(ns auto-ap.datomic.migrate.invoice-converter
  (:require [datomic.api :as d]))

(def add-matches
  [[{:db/ident :client/matches
     :db/valueType :db.type/string
     :db/cardinality :db.cardinality/many
     :db/doc "The strings that match the client"}
    {:db/ident :client/location-matches
     :db/valueType :db.type/ref
     :db/cardinality :db.cardinality/many
     :db/isComponent true
     :db/doc "The mapping from string to location"}

    {:db/ident :location-match/matches
     :db/valueType :db.type/string
     :db/cardinality :db.cardinality/many
     :db/doc "The strings that match the location"}

    {:db/ident :location-match/location
     :db/valueType :db.type/string
     :db/cardinality :db.cardinality/one
     :db/doc "The location of the location match"}
    ]])

(defn add-starter [conn]
  (if (seq (d/query {:query {:find '[?e]
                               :in ['$]
                               :where ['[?e :client/code "CBC"]]}
                       :args [(d/db conn)]}))
    [[{:db/id [:client/code "CBC"]
       :client/matches ["campbell brewing company"]
       :client/location-matches [{:location-match/location "CB"
                                  :location-match/matches ["campbell brewing company"]}]}]]
    [[]]))

(defn add-default-location [conn]
  [[{:db/ident :client/default-location
     :db/valueType :db.type/string
     :db/cardinality :db.cardinality/one
     :db/doc "The default location if one can't be found"}]])

(defn add-default-location-2 [conn]
  (if (seq (d/query {:query {:find '[?e]
                             :in ['$]
                             :where ['[?e :client/code "CBC"]]}
                     :args [(d/db conn)]}))
    [[{:db/id [:client/code "CBC"]
       :client/default-location "CB"}]]
    [[]]))

(def add-import-status
  [[{:db/ident :invoice/import-status
     :db/valueType :db.type/ref
     :db/cardinality :db.cardinality/one
     :db/doc "The status of importing the transaction"}

    {:db/ident :import-status/pending}
    {:db/ident :import-status/imported}]])

(defn add-import-status-existing-invoices [conn]
  (let [existing-invoices (->> (d/query {:query {:find ['?e]
                                                 :in ['$]
                                                 :where ['[?e :invoice/invoice-number]]}
                                         :args [(d/db conn)]}))]
    [(map (fn [i] {:db/id (first i)
                   :invoice/import-status :import-status/imported})
          existing-invoices)]))
