(ns auto-ap.jobs.close-auto-invoices
  (:require
   [auto-ap.datomic :refer [conn]]
   [auto-ap.jobs.core :refer [execute]]
   [auto-ap.time :as time]
   [clj-time.coerce :as coerce]
   [auto-ap.logging :as alog]
   [datomic.api :as dc]))

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

                                (mapv (fn [[i]] {:db/id                       i
                                                 :invoice/outstanding-balance 0.0
                                                 :invoice/status              :invoice-status/paid}))
                                ))

    (alog/info ::closed :count (count invoices-to-close))))


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