(ns ajet-chat.e2e.debug-route
  "Debug script to test OAuth flow with localhost URLs."
  (:require ["playwright" :as pw]
            [ajet-chat.e2e.config :as config]
            [ajet-chat.e2e.helpers :as h]
            [ajet-chat.e2e.setup :as setup]
            [promesa.core :as p]))

(defn -main [& _args]
  (p/let [;; Setup Gitea + OAuth
          oauth-creds (setup/setup-gitea-and-provider!)
          _           (js/console.log "[debug] OAuth creds:" (clj->js oauth-creds))

          ;; Launch browser
          browser (h/launch-browser!)
          context (h/new-context! browser)
          page    (h/new-page! context)]

    (-> (p/do
          ;; Log requests for debugging
          (.on page "request" (fn [req]
                                (js/console.log (str "[req] " (.method req) " " (.url req)))))
          (.on page "requestfailed" (fn [req]
                                      (js/console.log (str "[FAIL] " (.url req) " - "
                                                           (.-errorText (.failure req))))))

          ;; Navigate to setup
          (h/goto page "/")
          (js/console.log "[debug] URL after goto /:" (.url page))

          (h/wait-for-url page #"/setup" {:timeout 10000})

          ;; Fill provider form with localhost:4080 URL
          (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)
          (js/console.log "[debug] Form filled with base-url:" config/gitea-url)

          (h/click page "button:has-text('Add Provider')")
          (h/wait-for-url page #"/auth/login" {:timeout 10000})
          (js/console.log "[debug] On login page:" (.url page))

          ;; Click Gitea provider
          (h/wait-for-selector page "a[href*='provider=gitea-test']")
          (h/click page "a[href*='provider=gitea-test']")

          ;; Wait for Gitea login form
          (h/wait-for-selector page "#user_name, input[name='user_name']"
                               {:timeout 15000})
          (js/console.log "[debug] On Gitea login form! URL:" (.url page))
          (h/screenshot! page "debug-gitea-login.png")

          ;; Fill Gitea login
          (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')")
          (js/console.log "[debug] Submitted Gitea login, waiting...")

          ;; Handle OAuth authorization page
          (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
              (js/console.log "[debug] Found authorize button, clicking...")
              (.click auth-btn)))

          ;; Wait for redirect back to ajet-chat
          (h/wait-for-url page #"localhost:4000" {:timeout 30000})
          (js/console.log "[debug] Back on ajet-chat! URL:" (.url page))
          (h/screenshot! page "debug-back-on-app.png")

          (js/console.log "[debug] SUCCESS!"))

        (p/catch (fn [err]
                   (p/do
                     (js/console.error "[debug] Error:" (.-message err))
                     (js/console.log "[debug] URL at error:" (.url page))
                     (h/screenshot! page "debug-error.png"))))
        (p/finally (fn []
                     (h/close-all! browser)
                     (js/console.log "[debug] Browser closed"))))))
