(ns auto-ap.graphql.reports
  (:require
   [amazonica.aws.s3 :as s3]
   [auto-ap.datomic :refer [conn]]
   [auto-ap.datomic.reports :as r]
   [auto-ap.graphql.utils
    :refer [<-graphql assert-admin attach-tracing-resolvers result->page]]
   [config.core :refer [env]]
   [datomic.client.api :as dc]))

(defn get-report-page [context args _]
  (let [args                                    (assoc args :id (:id context))
        [reports reports-count] (r/get-graphql (assoc (<-graphql (:filters args))
                                                                      :id (:id context)))]
    (result->page reports reports-count :reports (:filters args)))
  )

(defn delete-report [context args _]
  (assert-admin (:id context))
  (let [[id-to-delete key] (first (dc/q '[:find ?i ?k
                                           :in $ ?i
                                           :where [?i :report/key ?k]]
                                         (dc/db conn)
                                         (:id args)))]
    (when id-to-delete 
      (s3/delete-object :bucket-name (:data-bucket env)
                        :key key)
      (dc/transact conn {:tx-data [[:db/retractEntity id-to-delete]]}))
    {:message (format "deleted %s successfully" key)}))




(def objects
  {:report
   {:fields {:url {:type 'String}
             :name {:type 'String}
             :created {:type :iso_date}
             :creator {:type 'String}
             :id {:type :id}}}

   :report_page
   {:fields {:reports {:type '(list :report)}
             :count           {:type 'Int}
             :total           {:type 'Int}
             :start           {:type 'Int}
             :end             {:type 'Int}}}})

(def queries
  {:report_page {:type    :report_page
                 :args    {:filters {:type :report_filters}}
                 :resolve :get-report-page}})

(def mutations
  {:delete_report {:type    :message
                   :args    {:id {:type :id}}
                   :resolve :mutation/delete-report}})

(def input-objects
  {:report_filters
   {:fields {:client_id         {:type :id}
             :start             {:type 'Int}
             :per_page          {:type 'Int}
             :sort              {:type '(list :sort_item)}}}})

(def enums
  {})

(def resolvers
  {:get-report-page get-report-page
   :mutation/delete-report delete-report})


(defn attach [schema]
  (-> 
   (merge-with merge schema
               {:objects objects
                :queries queries
                :mutations mutations
                :input-objects input-objects
                :enums enums})
   (attach-tracing-resolvers resolvers)))
