(ns auto-ap.datomic.reports
  (:require
   [auto-ap.datomic
    :refer [add-sorter-fields
            apply-pagination
            apply-sort-3
            conn
            merge-query
            pull-many]]
   [auto-ap.graphql.utils :refer [can-see-client? limited-clients]]
   [clj-time.coerce :as c]
   [datomic.client.api :as dc]))

(defn raw-graphql-ids [db args]
  (let [query (cond-> {:query {:find []
                               :in ['$ ]
                               :where []}
                       :args [db]} 

                
                (:client-id args) 
                (merge-query {:query {:in ['?client-id]
                                      :where ['[?e :report/client ?client-id]]}
                              :args [(:client-id args)]})

                (limited-clients (:id args))
                (merge-query {:query {:in ['[?xx ...]]
                                      :where ['[?e :report/client ?xx]]}
                              :args [(set (map :db/id (limited-clients (:id args))))]})
                (:sort args) (add-sorter-fields {"client" ['[?e :report/client ?c]
                                                           '[?c :client/name ?sort-client]]
                                                 "created" ['[?e :report/created ?sort-created]]
                                                 "creator" ['[?e :report/creator ?sort-creator]]
                                                 "name" ['[?e :report/name ?sort-name]
                                                           ]}
                                                args)

                true
                (merge-query {:query {:find ['?sort-default '?e] :where ['[?e :report/created ?sort-default]]}}))]
    (->> query
      (dc/q)
      (apply-sort-3 (update args :sort conj {:sort-key "default-2" :asc true}))
      (apply-pagination args))))

(defn graphql-results [ids db args]
  (let [results (->> (pull-many db '[:db/id :report/client :report/created :report/url :report/name :report/creator]
                                  ids)
                     (map #(update % :report/created c/from-date))
                     (group-by :db/id))]
    (->> ids
         (map results)
         (filter identity)
         
         (map first)
         (filter (fn [r]
                   (every?
                     #(can-see-client? (:id args) %)
                     (map :db/id (:report/client r))))))))

(defn get-graphql [args]
  (let [db (dc/db conn)
        {ids-to-retrieve :ids matching-count :count} (raw-graphql-ids db args)]
    
    [(->> (graphql-results ids-to-retrieve db args))
     matching-count]))





