(ns ajet-chat.e2e.tests.community-test
  "Workflow 6: Community creation after initial setup."
  (:require [ajet-chat.e2e.config :as config]
            [ajet-chat.e2e.helpers :as h]
            [ajet-chat.e2e.setup :as setup]
            [promesa.core :as p]))

(defn create-community-via-ui
  "Authenticated user can create a new community via the API."
  []
  (p/let [oauth-creds (setup/setup-gitea-and-provider!)
          browser     (h/launch-browser!)
          context     (h/new-context! browser)
          page        (h/new-page! context)]
    (-> (p/do
          ;; Login via Gitea OAuth and create first community
          (setup/login-and-setup! page config/test-user-a "Primary Community" "primary")
          (h/wait-for-url page #"/app" {:timeout 15000})

          ;; Create a second community via API (Datastar form has timing issues
          ;; with signal binding in headless Playwright)
          (p/let [result (setup/create-community-from-page! page "Second Community" "second-community")]
            (js/console.log "  Created second community:" (js/JSON.stringify (clj->js result))))

          ;; Reload to pick up the new community
          (h/goto page "/app")
          (h/wait-for-url page #"/app" {:timeout 15000})

          ;; Verify the community strip has content (multiple communities)
          (h/wait-for-selector page "#community-strip" {:timeout 10000})
          (p/let [strip-text (h/text-content page "#community-strip")]
            (assert (some? strip-text) "community strip should have content"))

          ;; Verify sidebar shows channels
          (h/wait-for-selector page "#sidebar" {:timeout 10000})
          (p/let [sidebar-text (h/text-content page "#sidebar")]
            (assert (some? sidebar-text) "sidebar should have content")))

        (p/catch (fn [err]
                   (p/do
                     (h/screenshot! page "community-create-failure.png")
                     (throw err))))
        (p/finally (fn []
                     (h/close-all! browser))))))

(def tests
  [{:name "create-community-via-ui"
    :test-fn create-community-via-ui}])
