(ns ajet-chat.e2e.debug
  (: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 [_ (setup/setup-gitea-and-provider!)
            browser (h/launch-browser!)
            context (h/new-context! browser)
            page (h/new-page! context)]
      (p/do
        (setup/login-via-gitea! page config/test-user-a)
        (h/wait-for-url page #"/(app|setup)" {:timeout 30000})
        (js/console.log "After login URL:" (h/page-url page))

        (h/goto page "/setup")
        (h/wait-ms 2000)
        (js/console.log "On /setup URL:" (h/page-url page))
        (h/screenshot! page "debug-setup-page.png")

        ;; Check page HTML for form type
        (p/let [form-html (h/evaluate page "document.querySelector('form')?.outerHTML?.substring(0, 200)")]
          (js/console.log "Form HTML:" form-html))

        (h/wait-for-selector page "input[name='name']")
        (h/wait-ms 1500)
        (h/type-text page "input[name='name']" "Debug Community")
        (h/type-text page "input[name='slug']" "debug-community")
        (h/screenshot! page "debug-filled-form.png")

        ;; Click submit
        (h/click page "button[type='submit']")
        (h/wait-ms 5000)
        (js/console.log "After submit URL:" (h/page-url page))
        (h/screenshot! page "debug-after-submit.png")

        ;; Check for any error message on page
        (p/let [error-text (p/catch
                             (h/text-content page "#setup-error")
                             (fn [_] nil))]
          (js/console.log "Setup error:" error-text))

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