(ns auto-ap.jobs.close-auto-invoices
  (:gen-class)
  (:require
   [auto-ap.datomic :refer [conn]]
   [auto-ap.jobs.core :refer [execute]]
   [auto-ap.time :as time]
   [clj-time.coerce :as coerce]
   [clojure.tools.logging :as log]
   [datomic.client.api :as dc]))

(defn close-auto-invoices []
  (let [invoices-to-close (dc/q {:query {:find  ['?e]
                                            :in    ['$ '?today]
                                            :where ['[?e :invoice/scheduled-payment ?d]
                                                    '[?e :invoice/status :invoice-status/unpaid]
                                                    '[(<= ?d ?today)]]}
                                    :args  [(dc/db conn) (coerce/to-date (time/local-now))]})]
    (log/info "Closing " (count invoices-to-close) "scheduled invoices")
    (dc/transact conn {:tx-data (some->> invoices-to-close
                                         seq

                                         (mapv (fn [[i]] {:db/id                       i
                                                          :invoice/outstanding-balance 0.0
                                                          :invoice/status              :invoice-status/paid}))
                                         )})
    (log/info "Closed " (count invoices-to-close) "scheduled invoices")))


(defn -main [& _]
  (execute "close-auto-invoices" close-auto-invoices))
