(ns iol-ion.tx.propose-invoice
  (:require [datomic.api :as dc]))

(defn propose-invoice [db invoice]
  (let [existing? (boolean (seq (dc/q '[:find  ?i
                                        :in    $ ?invoice-number ?client ?vendor
                                        :where
                                        [?i :invoice/invoice-number ?invoice-number]
                                        [?i :invoice/client ?client]
                                        [?i :invoice/vendor ?vendor]
                                        (not [?i :invoice/status :invoice-status/voided])]
                                      db
                                      (:invoice/invoice-number invoice)
                                      (:invoice/client invoice)
                                      (:invoice/vendor invoice))))
        [ locked-until] (first (dc/q '[:find ?locked-until
                                       :in $ ?c
                                       :where [?c :client/locked-until ?locked-until]]
                                     db
                                     (:invoice/client invoice)))
        is-locked? (cond
                     (not locked-until) false
                     (not (:invoice/date invoice)) true
                     (< (compare (:invoice/date invoice) locked-until) 0) true
                     :else false)]
    (if (or existing? is-locked?)
      []
      [[:upsert-invoice invoice]])))
