(ns auto-ap.routes.auth
  (:require [auto-ap.db.users :as users]
            [buddy.sign.jwt :as jwt]
            [clj-http.client :as http]
            [clj-time.core :as time]
            [compojure.core :refer [GET defroutes]]
            [config.core :refer [env]]))

(def google-client-id "264081895820-0nndcfo3pbtqf30sro82vgq5r27h8736.apps.googleusercontent.com")
(def google-client-secret "OC-WemHurPXYpuIw5cT-B90g")

(defroutes routes
  (GET "/oauth" {{:strs [code]} :query-params :keys [scheme] :as r {:strs [host]} :headers}
       (try
         (let [auth (-> "https://accounts.google.com/o/oauth2/token"
                        (http/post 
                         {:form-params {"client_id" google-client-id
                                        "client_secret" google-client-secret
                                        "code" code
                                        "redirect_uri" (str (:scheme env) "://" host  "/api/oauth")
                                        "grant_type" "authorization_code"}
                          :as :json})
                        :body)
               _ (println auth)
               token (:access_token auth)
               profile (-> (http/get "https://www.googleapis.com/oauth2/v1/userinfo"
                                     {:headers {"Authorization" (str "Bearer " token)} :as :json})
                           :body
                           (doto println))
               user (users/find-or-insert! {:provider "google"
                                            :provider-id (:id profile)
                                            :role "none"
                                            :name (:name profile)})]
           
           (if (and token user)
             {:status 301
              :headers {"Location" (str "/?jwt=" (jwt/sign {:user "test"
                                                            :exp (time/plus (time/now) (time/days 7))
                                                            :companies (:companies user)
                                                            :role (:role user)
                                                            :name (:name profile)}
                                                           (:jwt-secret env)
                                                           {:alg :hs512}))}}
             {:status 401
              :body "Couldn't authenticate"}))
         (catch Exception e
           
           {:status 401
            :body (str "Couldn't authenticate "  (.toString e))}))))
