package webui

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"mailgoserver/internal/db"
)

// TestSeedDefaultAdminMustChangeUsername confirms the seeded "admin" account is still
// forced through the full username+password change on first login.
func TestSeedDefaultAdminMustChangeUsername(t *testing.T) {
	app := newTestApp(t)
	if err := app.DB.SeedDefaultAdminIfEmpty(); err != nil {
		t.Fatal(err)
	}
	mux := app.Mux()

	form := url.Values{"username": {db.DefaultAdminUsername}, "password": {db.DefaultAdminPassword}}
	req := httptest.NewRequest(http.MethodPost, Prefix+"/login", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	cookie := sessionCookieFrom(t, rec)

	// The forced-redirect page must show a username field.
	req = httptest.NewRequest(http.MethodGet, Prefix+"/", nil)
	req.AddCookie(cookie)
	rec = httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	if rec.Code != http.StatusFound || rec.Header().Get("Location") != Prefix+"/first-login" {
		t.Fatalf("expected redirect to /first-login, got %d Location=%q", rec.Code, rec.Header().Get("Location"))
	}
	req = httptest.NewRequest(http.MethodGet, Prefix+"/first-login", nil)
	req.AddCookie(cookie)
	rec = httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	if !strings.Contains(rec.Body.String(), `name="username"`) {
		t.Error("default admin's first-login page should still ask for a new username")
	}

	// Submitting without a username must fail — it's still required for this account.
	form = url.Values{"password": {"BrandNewPassw0rd!"}, "password_confirm": {"BrandNewPassw0rd!"}}
	req = httptest.NewRequest(http.MethodPost, Prefix+"/first-login", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(cookie)
	rec = httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Choose a username") {
		t.Fatalf("expected a 'choose a username' validation error, got %d: %s", rec.Code, rec.Body.String())
	}

	// With a username, it succeeds and the account is fully usable.
	form = url.Values{"username": {"realadmin"}, "password": {"BrandNewPassw0rd!"}, "password_confirm": {"BrandNewPassw0rd!"}}
	req = httptest.NewRequest(http.MethodPost, Prefix+"/first-login", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(cookie)
	rec = httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	if rec.Code != http.StatusFound || rec.Header().Get("Location") != Prefix+"/" {
		t.Fatalf("expected redirect to dashboard, got %d Location=%q", rec.Code, rec.Header().Get("Location"))
	}
}

// TestDelegatedAdminOnlyChangesPassword confirms an admin created through the
// delegation flow (addAdmin) — who already picked their own username at creation
// time — is only ever asked for a new password on first login, never a username.
func TestDelegatedAdminOnlyChangesPassword(t *testing.T) {
	app := newTestApp(t)
	mux := app.Mux()

	hash, err := db.HashPassword("initial-temp-password-1!")
	if err != nil {
		t.Fatal(err)
	}
	userID, err := app.DB.CreateScopedAdminUser("delegate-bob", hash, 0, nil)
	if err != nil {
		t.Fatal(err)
	}
	token, err := app.DB.CreateSession(userID, true, sessionTTL)
	if err != nil {
		t.Fatal(err)
	}
	cookie := &http.Cookie{Name: sessionCookieName, Value: token}

	req := httptest.NewRequest(http.MethodGet, Prefix+"/first-login", nil)
	req.AddCookie(cookie)
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("first-login page: status=%d", rec.Code)
	}
	if strings.Contains(rec.Body.String(), `name="username"`) {
		t.Error("a delegated admin's first-login page should not ask for a new username")
	}

	form := url.Values{"password": {"BrandNewPassw0rd!"}, "password_confirm": {"BrandNewPassw0rd!"}}
	req = httptest.NewRequest(http.MethodPost, Prefix+"/first-login", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(cookie)
	rec = httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	if rec.Code != http.StatusFound || rec.Header().Get("Location") != Prefix+"/" {
		t.Fatalf("expected redirect to dashboard, got %d Location=%q body=%s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
	}

	updated, err := app.DB.GetAdminUserByID(userID)
	if err != nil || updated == nil {
		t.Fatal(err)
	}
	if updated.Username != "delegate-bob" {
		t.Errorf("username changed unexpectedly to %q", updated.Username)
	}
	if updated.MustChangePassword {
		t.Error("must_change_password should be cleared after first login")
	}
	if !db.CheckPassword("BrandNewPassw0rd!", updated.PasswordHash) {
		t.Error("password was not actually updated")
	}
}

func sessionCookieFrom(t *testing.T, rec *httptest.ResponseRecorder) *http.Cookie {
	t.Helper()
	for _, c := range rec.Result().Cookies() {
		if c.Name == sessionCookieName {
			return c
		}
	}
	t.Fatal("no session cookie set")
	return nil
}
