(ns ajet.chat.e2e.auth-flow-e2e-test
  "E2E tests for auth gateway flows.
   Requires: docker compose -f docker-compose.test.yml --profile e2e up -d

   Tests hit the auth-gw HTTP endpoint at localhost:3100."
  (:require [clojure.test :refer [deftest testing is]]
            [babashka.http-client :as http]))

(def ^:private base-url (or (System/getenv "AJET_TEST_BASE_URL") "http://localhost:3100"))
(def ^:private no-redirect-client (http/client {:follow-redirects :never}))

;;; ---------------------------------------------------------------------------
;;; Health check
;;; ---------------------------------------------------------------------------

(deftest health-endpoint-returns-200
  (let [resp (http/get (str base-url "/health"))]
    (is (= 200 (:status resp)))
    (is (re-find #"ok" (:body resp)))))

;;; ---------------------------------------------------------------------------
;;; Login page
;;; ---------------------------------------------------------------------------

(deftest login-page-renders
  (let [resp (http/get (str base-url "/auth/login")
               {:throw false})]
    (is (= 200 (:status resp)))
    (is (re-find #"(?i)sign in|ajet chat" (:body resp)))))

;;; ---------------------------------------------------------------------------
;;; Auth required for protected routes
;;; ---------------------------------------------------------------------------

(deftest api-without-auth-returns-401
  (let [resp (http/get (str base-url "/api/communities")
               {:throw false})]
    (is (= 401 (:status resp)))))

(deftest web-without-auth-redirects-to-login
  (let [resp (http/get (str base-url "/app/home")
               {:throw  false
                :client no-redirect-client})]
    (is (= 302 (:status resp)))
    (is (re-find #"/auth/login" (get-in resp [:headers "location"] "")))))
