package main

import (
	"context"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
	"time"

	"github.com/chromedp/chromedp"
	"github.com/joho/godotenv"
)

// This opt-in test sends real browser form navigations through the launcher's
// HTTP headers and handlers. It uses temporary data and a fake database client;
// it never starts MariaDB, contacts licensing, or reads a member installation.
func TestBrowserLauncherForms(t *testing.T) {
	if os.Getenv("CHATLOOP_TEST_BROWSER") != "1" {
		t.Skip("set CHATLOOP_TEST_BROWSER=1 to run the browser regression")
	}
	listener, err := net.Listen("tcp", controlAddress)
	if err != nil {
		t.Fatal("browser test requires the launcher control port to be unused:", err)
	}
	t.Cleanup(func() { _ = listener.Close() })
	a := newLauncher(t.TempDir(), t.TempDir(), "browser-fixture-token")
	a.dbOwned = true
	a.set("Pengaturan pertama", nil, false, false)
	client := a.vendorBin("mariadb.exe")
	if err := os.MkdirAll(filepath.Dir(client), 0700); err != nil {
		t.Fatal(err)
	}
	source := filepath.Join(t.TempDir(), "database-client.go")
	if err := os.WriteFile(source, []byte("package main\nimport \"fmt\"\nfunc main() { fmt.Println(1) }\n"), 0600); err != nil {
		t.Fatal(err)
	}
	if output, err := exec.Command("go", "build", "-o", client, source).CombinedOutput(); err != nil {
		t.Fatalf("build database readiness fixture: %v: %s", err, output)
	}

	type submission struct {
		path, origin string
		status       int
	}
	posts := make(chan submission, 16)
	routes := a.routes()
	server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		reply := httptest.NewRecorder()
		routes.ServeHTTP(reply, r)
		for key, values := range reply.Header() {
			w.Header()[key] = values
		}
		w.WriteHeader(reply.Code)
		_, _ = io.Copy(w, reply.Body)
		if r.Method == http.MethodPost {
			posts <- submission{r.URL.Path, r.Header.Get("Origin"), reply.Code}
		}
	})}
	go func() { _ = server.Serve(listener) }()
	t.Cleanup(func() {
		_ = server.Close()
		a.work.Wait()
	})

	opts := append([]chromedp.ExecAllocatorOption{}, chromedp.DefaultExecAllocatorOptions[:]...)
	if browser := os.Getenv("CHROME_PATH"); browser != "" {
		opts = append(opts, chromedp.ExecPath(browser))
	}
	allocator, cancelAllocator := chromedp.NewExecAllocator(context.Background(), opts...)
	defer cancelAllocator()
	browser, cancelBrowser := chromedp.NewContext(allocator)
	defer cancelBrowser()
	ctx, cancel := context.WithTimeout(browser, 60*time.Second)
	defer cancel()
	run := func(actions ...chromedp.Action) {
		t.Helper()
		if err := chromedp.Run(ctx, actions...); err != nil {
			t.Fatal(err)
		}
	}
	submit := func(selector, path string, status int) {
		t.Helper()
		if _, err := chromedp.RunResponse(ctx, chromedp.Click(selector, chromedp.ByQuery)); err != nil {
			t.Fatal(err)
		}
		select {
		case post := <-posts:
			if post.path != path || post.status != status || post.origin != "http://"+controlAddress {
				t.Fatalf("browser form rejected: path=%s status=%d origin=%q; want %s status=%d and local origin", post.path, post.status, post.origin, path, status)
			}
		case <-ctx.Done():
			t.Fatal("browser form was not submitted:", ctx.Err())
		}
	}

	run(chromedp.Navigate("http://"+controlAddress+"/open"),
		chromedp.WaitVisible(`#license`, chromedp.ByQuery),
		chromedp.SetValue(`#license`, "WA-BROWSER-FIXTURE", chromedp.ByQuery),
		chromedp.SetValue(`#username`, "browser_user", chromedp.ByQuery),
		chromedp.SetValue(`#password`, "BrowserPassword_123!", chromedp.ByQuery),
		chromedp.SetValue(`#confirm`, "DifferentPassword_123!", chromedp.ByQuery))
	submit(`form[action="/setup"] button`, "/setup", http.StatusUnprocessableEntity)
	var message, username, key, password string
	run(chromedp.WaitVisible(`[role="alert"]`, chromedp.ByQuery),
		chromedp.Text(`[role="alert"]`, &message, chromedp.ByQuery),
		chromedp.Value(`#username`, &username, chromedp.ByQuery),
		chromedp.Value(`#license`, &key, chromedp.ByQuery),
		chromedp.Value(`#password`, &password, chromedp.ByQuery))
	if message != "Ulangan password berbeda." || username != "browser_user" || key != "WA-BROWSER-FIXTURE" || password != "" {
		t.Fatal("invalid setup must show the field error, preserve username/license, and clear passwords")
	}
	if _, err := os.Stat(filepath.Join(a.data, ".env")); !os.IsNotExist(err) {
		t.Fatal("invalid form must not create settings")
	}
	run(chromedp.SetValue(`#password`, "BrowserPassword_123!", chromedp.ByQuery),
		chromedp.SetValue(`#confirm`, "BrowserPassword_123!", chromedp.ByQuery))
	submit(`form[action="/setup"] button`, "/setup", http.StatusSeeOther)
	a.work.Wait()
	settings, err := godotenv.Read(filepath.Join(a.data, ".env"))
	if err != nil || settings["SUPERADMIN_USERNAME"] != "browser_user" || settings["SUPERADMIN_PASSWORD"] != "BrowserPassword_123!" || settings["LICENSE_KEY"] != "WA-BROWSER-FIXTURE" {
		t.Fatal("valid browser setup did not save the account and license")
	}

	// The backend is deliberately absent. Retry and license replacement still
	// exercise the real control handlers without any external activation.
	run(chromedp.Navigate("http://"+controlAddress+"/"),
		chromedp.WaitVisible(`form[action="/retry"] button`, chromedp.ByQuery))
	submit(`form[action="/retry"] button`, "/retry", http.StatusSeeOther)
	a.work.Wait()
	run(chromedp.Navigate("http://"+controlAddress+"/"),
		chromedp.Click(`details summary`, chromedp.ByQuery),
		chromedp.SetValue(`#license`, "WA-BROWSER-REPLACED", chromedp.ByQuery))
	submit(`form[action="/license"] button`, "/license", http.StatusSeeOther)
	a.work.Wait()
	updated, err := godotenv.Read(filepath.Join(a.data, ".env"))
	if err != nil || updated["LICENSE_KEY"] != "WA-BROWSER-REPLACED" || updated["JWT_SECRET"] != settings["JWT_SECRET"] || updated["DB_PASS"] != settings["DB_PASS"] || updated["SUPERADMIN_PASSWORD"] != settings["SUPERADMIN_PASSWORD"] {
		t.Fatal("license replacement must preserve the account and installation secrets")
	}
	run(chromedp.Navigate("http://" + controlAddress + "/"))
	submit(`form[action="/stop"] button`, "/stop", http.StatusOK)
	if !a.stopping() {
		t.Fatal("close button did not request shutdown")
	}
}
