(ns auto-ap.integration.graphql.vendors
  (:require [auto-ap.graphql.vendors :as sut2]
            [auto-ap.datomic :refer [uri conn]]
            [auto-ap.datomic.migrate :as m]
            
            [clojure.test :as t :refer [deftest is testing use-fixtures]]
            [datomic.api :as d]
            [clj-time.core :as time]))

(defn wrap-setup
  [f]
  (with-redefs [auto-ap.datomic/uri "datomic:mem://datomic-transactor:4334/invoice"]
    (d/create-database uri)
    (with-redefs [auto-ap.datomic/conn (d/connect uri)]
      (m/migrate conn)
      (f)
      (d/release conn)
      (d/delete-database uri))))    

(defn admin-token []
  {:user "TEST ADMIN"
   :exp (time/plus (time/now) (time/days 1))
   :user/role "admin"
   :user/name "TEST ADMIN"})

(defn user-token [client-id]
  {:user "TEST USER"
   :exp (time/plus (time/now) (time/days 1))
   :user/role "user"
   :user/name "TEST USER"
   :user/clients [{:db/id client-id}]})





(defn new-invoice [args]
  (merge {:invoice/total 100.0
          :invoice/invoice-number (.toString (java.util.UUID/randomUUID))}
         args))

(use-fixtures :each wrap-setup)


(deftest vendors
  (testing "vendors"
    (let [{:strs [vendor client]} (:tempids @(d/transact (d/connect uri) [{:vendor/name "Test" :db/id "vendor"}
                                                                          {:db/id "client"
                                                                           :client/code "DEF"}]))]
      (testing "it should find vendors"
        (let [result (sut2/get-graphql {} {} {})]
          (is (= 1 (count result)))))

      (testing "It should count invoice usages for each client"
        @(d/transact (d/connect uri)
                     [{:invoice/client client
                       :invoice/invoice-number "123"
                       :invoice/vendor vendor}])

        
        (let [result (sut2/get-graphql {:id (admin-token)} {} {})]
          (is (= [{:client_id client
                   :count 1}] (-> result first :usage)))))

      (testing "It should count transaction usages for each client"
        @(d/transact (d/connect uri)
                     [{:transaction/client client
                       :transaction/vendor vendor}])
        (let [result (sut2/get-graphql {:id (admin-token)} {} {})]
          (is (= [{:client_id client
                   :count 2}] (-> result first :usage)))))

      (testing "It should limit usages to visible clients"
        (let [result (sut2/get-graphql {:id (user-token client)} {} {})]
          (is (= [{:client_id client
                   :count 2}] (-> result first :usage))))

        (let [result (sut2/get-graphql {:id (user-token 0)} {} {})]
          (is (= nil (-> result first :usage))))))))


