(ns ajet-chat.e2e.debug-msg
  (:require [ajet-chat.e2e.setup :as setup]
            [ajet-chat.e2e.helpers :as h]
            [ajet-chat.e2e.config :as config]
            [promesa.core :as p]))

(-> (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
        ;; Capture ALL network requests
        (.on page "request" (fn [req]
                              (let [url (.url req)]
                                (when (or (re-find #"/sse" url)
                                          (re-find #"/web/" url)
                                          (re-find #"/api/" url))
                                  (js/console.log "[req]" (.method req) url)))))
        (.on page "response" (fn [resp]
                               (let [url (.url resp)]
                                 (when (or (re-find #"/sse" url)
                                           (re-find #"/web/" url))
                                   (js/console.log "[resp]" (.status resp) url
                                                   "headers:" (js/JSON.stringify (.headers resp)))))))
        (.on page "console" (fn [msg]
                              (when (= (.type msg) "error")
                                (js/console.log "[browser error]" (.text msg)))))

        ;; Full setup wizard
        (h/goto page "/")
        (h/wait-for-url page #"/setup" {:timeout 10000})
        (h/wait-for-selector page "select[name='provider-type']")
        (h/select-option page "select[name='provider-type']" "gitea")
        (h/fill page "input[name='display-name']" "Gitea Test")
        (h/fill page "input[name='slug']" "gitea-test")
        (h/fill page "input[name='client-id']" (:client-id oauth-creds))
        (h/fill page "input[name='client-secret']" (:client-secret oauth-creds))
        (h/fill page "input[name='base-url']" config/gitea-url)
        (h/click page "button:has-text('Add Provider')")
        (h/wait-for-url page #"/auth/login" {:timeout 10000})
        (h/click page "a[href*='provider=gitea-test']")
        (h/wait-for-selector page "#user_name" {:timeout 15000})
        (h/fill page "#user_name" (:username config/test-user-a))
        (h/fill page "#password" (:password config/test-user-a))
        (h/click page "button:has-text('Sign In')")
        (p/let [auth-btn (p/catch
                           (.waitForSelector page "button:has-text('Authorize Application'), button.ui.green.button"
                                             #js {:timeout 5000})
                           (fn [_] nil))]
          (when auth-btn (.click auth-btn)))
        (h/wait-for-url page #"/(setup|app)" {:timeout 30000})
        (p/let [url (h/page-url page)]
          (when (re-find #"/setup" url)
            (p/do
              (h/wait-for-selector page "input[name='name']")
              (h/fill page "input[name='name']" "Debug Community")
              (h/fill page "input[name='slug']" "debug-community")
              (h/click page "button[type='submit']")
              (h/wait-ms 2000))))
        (h/wait-for-url page #"/app" {:timeout 15000})
        (js/console.log "\n=== ON /app — waiting for SSE activity ===")

        ;; Wait 8 seconds to see if SSE connection is made
        (h/wait-ms 8000)

        ;; Check directly — make a manual fetch to /sse/events
        (js/console.log "\n=== Manual SSE test ===")
        (p/let [sse-test (h/evaluate page
                           "new Promise((resolve) => {
                              const ctrl = new AbortController();
                              setTimeout(() => ctrl.abort(), 3000);
                              fetch('/sse/events', {signal: ctrl.signal})
                                .then(r => resolve({status: r.status, ok: r.ok, headers: Object.fromEntries(r.headers.entries())}))
                                .catch(e => resolve({error: e.message}));
                            })")]
          (js/console.log "SSE fetch result:" (js/JSON.stringify (clj->js sse-test))))

        ;; Also check /web/health
        (p/let [health (h/evaluate page "fetch('/web/health').then(r => r.text())")]
          (js/console.log "Web-SM health:" health))

        (h/close-all! browser)))
    (.catch (fn [e]
              (js/console.error "Error:" (.-message e))))
    (.then (fn [_] (js/process.exit 0))))
