package main

import (
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestInitialEnvAndLicenseChangePreserveInstallationSecrets(t *testing.T) {
	first, err := initialEnv("WA-FIRST-123", "toko_utama", "AdminPassword_123!", strings.Repeat("a", 64))
	if err != nil {
		t.Fatal(err)
	}
	second, err := initialEnv("WA-SECOND-456", "toko_utama", "AdminPassword_123!", strings.Repeat("a", 64))
	if err != nil {
		t.Fatal(err)
	}
	if first == second || !strings.Contains(first, "DB_HOST=127.0.0.1\nDB_PORT=13306") {
		t.Fatal("first run must create a unique JWT and private local database settings")
	}
	updated, err := replaceLicense(first, "WA-NEW-789")
	if err != nil {
		t.Fatal(err)
	}
	if strings.Contains(updated, "WA-FIRST-123") || strings.Replace(first, "LICENSE_KEY=WA-FIRST-123", "LICENSE_KEY=WA-NEW-789", 1) != updated {
		t.Fatal("license rotation changed a JWT, database password, or admin password")
	}
	if _, err := initialEnv("bad\nDB_PASS=evil", "toko_utama", "AdminPassword_123!", strings.Repeat("a", 64)); err == nil {
		t.Fatal("license must not inject environment lines")
	}
}

func savedLauncher(t *testing.T) (*launcher, string) {
	t.Helper()
	data := t.TempDir()
	contents, err := initialEnv("WA-SAVED-PRIVATE", "toko_utama", "PrivatePassword_123!", strings.Repeat("a", 64))
	if err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(data, ".env"), []byte(contents), 0600); err != nil {
		t.Fatal(err)
	}
	return newLauncher(t.TempDir(), data, "known-token"), contents
}

func TestReopenUsesSavedSettingsAndShowsProgressImmediately(t *testing.T) {
	a, original := savedLauncher(t)
	// Simulate a browser arriving before the startup goroutine has run.
	for i := 0; i < 2; i++ {
		a = newLauncher(a.root, a.data, "known-token")
		settings, err := a.installation()
		if err != nil || !settings.Configured || !settings.LicenseSaved || settings.Username != "toko_utama" {
			t.Fatal("reopen lost the saved installation")
		}
		w := httptest.NewRecorder()
		a.page(w, httptest.NewRequest(http.MethodGet, "http://"+controlAddress+"/open", nil))
		body := w.Body.String()
		if w.Code != 200 || !strings.Contains(body, `http-equiv="refresh"`) || !strings.Contains(body, "toko_utama") {
			t.Fatal("initial page must refresh and identify the saved account")
		}
		for _, forbidden := range []string{`name="license"`, `action="/setup"`, "WA-SAVED-PRIVATE", "PrivatePassword_123!"} {
			if strings.Contains(body, forbidden) {
				t.Fatal("reopen exposed a secret or requested activation again")
			}
		}
	}
	current, err := os.ReadFile(filepath.Join(a.data, ".env"))
	if err != nil || string(current) != original {
		t.Fatal("reopen changed saved credentials")
	}
}

func TestReadyOpenCarriesOnlyUsernameToLogin(t *testing.T) {
	a, _ := savedLauncher(t)
	a.set("ChatLoop siap digunakan.", nil, false, true)
	w := httptest.NewRecorder()
	a.page(w, httptest.NewRequest(http.MethodGet, "http://"+controlAddress+"/open", nil))
	if w.Code != http.StatusSeeOther || w.Header().Get("Location") != "http://127.0.0.1:13303/login?local=1&username=toko_utama" {
		t.Fatal("launcher did not open login with the saved username")
	}
	w = httptest.NewRecorder()
	a.page(w, httptest.NewRequest(http.MethodGet, "http://"+controlAddress+"/", nil))
	if w.Code != 200 || !strings.Contains(w.Body.String(), "Buka ChatLoop") {
		t.Fatal("control page must remain available without redirecting")
	}
}

func TestSavedInstallationHasRetryAndOptionalLicenseChange(t *testing.T) {
	a, _ := savedLauncher(t)
	a.set("Aplikasi belum siap", nil, false, false)
	w := httptest.NewRecorder()
	a.page(w, httptest.NewRequest(http.MethodGet, "http://"+controlAddress+"/", nil))
	body := w.Body.String()
	if !strings.Contains(body, `action="/retry"`) || !strings.Contains(body, "Lisensi tersimpan") || strings.Contains(body, `action="/setup"`) || strings.Contains(body, "<details open>") {
		t.Fatal("a failed startup must offer retry, not require a new license")
	}
}

func TestNewSetupMakesUsernameVisible(t *testing.T) {
	a := newLauncher(t.TempDir(), t.TempDir(), "known-token")
	a.dbOwned = true
	a.set("Pengaturan pertama", nil, false, false)
	w := httptest.NewRecorder()
	a.page(w, httptest.NewRequest(http.MethodGet, "http://"+controlAddress+"/open", nil))
	if !strings.Contains(w.Body.String(), `name="username"`) || !strings.Contains(w.Body.String(), `value="superadmin"`) {
		t.Fatal("first setup must show the account used for login")
	}
}

func TestSetupCannotOverwriteExistingInstallation(t *testing.T) {
	a, original := savedLauncher(t)
	a.set("Siap", nil, false, false)
	r := httptest.NewRequest(http.MethodPost, "http://"+controlAddress+"/setup", strings.NewReader("csrf=known-token&username=other&license=WA-OTHER"))
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	w := httptest.NewRecorder()
	a.setup(w, r)
	current, err := os.ReadFile(filepath.Join(a.data, ".env"))
	if err != nil || string(current) != original || w.Code != http.StatusSeeOther {
		t.Fatal("repeat setup must preserve the existing installation")
	}
}

func TestUnreadableConfigurationNeverLeaksOrAppearsAsNewSetup(t *testing.T) {
	a, _ := savedLauncher(t)
	if err := os.WriteFile(filepath.Join(a.data, ".env"), []byte("LICENSE_KEY=\"PRIVATE_UNCLOSED_VALUE"), 0600); err != nil {
		t.Fatal(err)
	}
	a.set("Siap", nil, false, false)
	w := httptest.NewRecorder()
	a.page(w, httptest.NewRequest(http.MethodGet, "http://"+controlAddress+"/", nil))
	if !strings.Contains(w.Body.String(), "Pengaturan lokal tidak bisa dibaca") || strings.Contains(w.Body.String(), "PRIVATE_UNCLOSED_VALUE") || strings.Contains(w.Body.String(), `action="/setup"`) {
		t.Fatal("broken settings must be preserved and their contents must stay private")
	}
}

func TestUsernameCannotInjectEnvironmentAndPasswordsMatchBootstrapPolicy(t *testing.T) {
	for _, username := range []string{"", "ab", "admin\nDB_PASS=bad", "admin user", strings.Repeat("a", 65)} {
		if _, err := initialEnv("WA-VALID-123", username, "PrivatePassword_123!", strings.Repeat("a", 64)); err == nil {
			t.Fatal("invalid username accepted")
		}
	}
	for _, password := range []string{"superadmin123", "password1234", "changeme123456"} {
		if _, err := initialEnv("WA-VALID-123", "superadmin", password, strings.Repeat("a", 64)); err == nil {
			t.Fatal("password rejected by backend must also be rejected by setup")
		}
	}
}

func TestStartRequestsCannotOverlap(t *testing.T) {
	a := newLauncher(t.TempDir(), t.TempDir(), "token")
	if a.begin("Starting") {
		t.Fatal("startup is already in progress")
	}
	a.set("Stopped", nil, false, false)
	if !a.begin("Starting") || a.begin("Starting again") {
		t.Fatal("only one start request may own startup")
	}
}

func TestRuntimeFolderAndOriginalPackageLayout(t *testing.T) {
	a := newLauncher(t.TempDir(), t.TempDir(), "token")
	if a.bundlePath("chatloop-server.exe") != filepath.Join(a.root, "chatloop-server.exe") {
		t.Fatal("original preview layout no longer supported")
	}
	if err := os.Mkdir(filepath.Join(a.root, "runtime"), 0700); err != nil {
		t.Fatal(err)
	}
	if a.vendorBin("mariadb.exe") != filepath.Join(a.root, "runtime", "mariadb", "bin", "mariadb.exe") {
		t.Fatal("runtime folder layout not selected")
	}
}

func TestRuntimeStateNeverReplacesExistingDatabase(t *testing.T) {
	data := t.TempDir()
	a := &launcher{data: data}
	first, err := a.loadOrCreateRuntime()
	if err != nil {
		t.Fatal(err)
	}
	second, err := a.loadOrCreateRuntime()
	if err != nil || first.DBPassword != second.DBPassword {
		t.Fatal("restart must keep the database password")
	}
	other := &launcher{data: t.TempDir()}
	if err := os.MkdirAll(filepath.Join(other.data, "mysql"), 0700); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(other.data, "mysql", "ibdata1"), []byte("existing"), 0600); err != nil {
		t.Fatal(err)
	}
	if _, err := other.loadOrCreateRuntime(); err == nil {
		t.Fatal("existing database without runtime state must never receive a new password")
	}
}

func TestLocalControlRequiresHostOriginAndCSRF(t *testing.T) {
	a := &launcher{data: t.TempDir(), csrf: "known-token", status: "Siap"}
	get := httptest.NewRequest(http.MethodGet, "http://"+controlAddress+"/", nil)
	response := httptest.NewRecorder()
	a.page(response, get)
	if response.Code != 200 || !strings.Contains(response.Body.String(), "known-token") {
		t.Fatal("local control page did not render its CSRF token")
	}
	for _, test := range []struct {
		name, method, host, origin, form string
		allowed                          bool
	}{
		{"local browser", "POST", controlAddress, "http://" + controlAddress, "csrf=known-token", true},
		{"no origin header", "POST", controlAddress, "", "csrf=known-token", true},
		{"opaque origin", "POST", controlAddress, "null", "csrf=known-token", false},
		{"foreign origin", "POST", controlAddress, "https://external.example", "csrf=known-token", false},
		{"different local port", "POST", controlAddress, "http://127.0.0.1:13303", "csrf=known-token", false},
		{"foreign host", "POST", "external.example:13330", "http://" + controlAddress, "csrf=known-token", false},
		{"old form token", "POST", controlAddress, "http://" + controlAddress, "csrf=old-token", false},
		{"missing token", "POST", controlAddress, "http://" + controlAddress, "", false},
		{"wrong method", "GET", controlAddress, "http://" + controlAddress, "csrf=known-token", false},
	} {
		t.Run(test.name, func(t *testing.T) {
			request := httptest.NewRequest(test.method, "http://"+test.host+"/setup", strings.NewReader(test.form))
			request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			request.Header.Set("Origin", test.origin)
			if a.authorizePost(request) != test.allowed {
				t.Fatal("incorrect local form authorization")
			}
		})
	}
}

func TestDiagnosticReportDoesNotIncludeCredentials(t *testing.T) {
	data := t.TempDir()
	if err := os.WriteFile(filepath.Join(data, ".env"), []byte("LICENSE_KEY=WA-PRIVATE-KEY\nSUPERADMIN_PASSWORD=private-password\n"), 0600); err != nil {
		t.Fatal(err)
	}
	a := &launcher{data: data, root: t.TempDir(), csrf: "known-token", status: "Siap"}
	request := httptest.NewRequest(http.MethodGet, "http://"+controlAddress+"/diagnostics?token=known-token", nil)
	response := httptest.NewRecorder()
	a.diagnostics(response, request)
	if response.Code != 200 || !strings.Contains(response.Body.String(), "Konfigurasi ada: true") {
		t.Fatal("diagnostic status was not generated")
	}
	if strings.Contains(response.Body.String(), "WA-PRIVATE-KEY") || strings.Contains(response.Body.String(), "private-password") {
		t.Fatal("diagnostic report exposed credentials")
	}
}
