(ns auto-ap.background.invoices
  (:require [auto-ap.datomic.invoices :as d-invoices]
            [auto-ap.datomic :refer [uri conn]]
            [datomic.api :as d]
            [auto-ap.time :as time]
            [clj-time.coerce :as coerce]
            [mount.core :as mount]
            [yang.scheduler :as scheduler]
            [unilog.context :as lc]
            [clojure.tools.logging :as log]))

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

                 (mapv (fn [[i]] {:db/id i
                                  :invoice/outstanding-balance 0.0
                                  :invoice/status :invoice-status/paid}))
                 (d/transact conn)
                 deref)
        (log/info "Closed " (count invoices-to-close) "scheduled invoices"))
      (catch Exception e
        (log/error e)))))

(mount/defstate close-auto-invoices-worker
  :start (scheduler/every 60000 close-auto-invoices)
  :stop (scheduler/stop close-auto-invoices-worker))
