package webui

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

func TestAuthCategoryMatches(t *testing.T) {
	cases := []struct {
		authType, category string
		want               bool
	}{
		{"admin_login", "admin", true},
		{"admin_mfa", "admin", true},
		{"webmail_login", "admin", false},
		{"webmail_login", "webmail", true},
		{"mailbox_mfa", "webmail", true},
		{"sender", "webmail", false},
		{"sender", "mailserver", true},
		{"mailbox", "mailserver", true},
		{"sender_validation", "mailserver", true},
		{"mailbox_validation", "mailserver", true},
		{"ip", "mailserver", true},
		{"imap_login", "mailserver", true},
		{"admin_login", "mailserver", false},
		{"anything", "", true},
		{"anything", "all", true},
	}
	for _, c := range cases {
		if got := authCategoryMatches(c.authType, c.category); got != c.want {
			t.Errorf("authCategoryMatches(%q, %q) = %v, want %v", c.authType, c.category, got, c.want)
		}
	}
}

// TestLogsAuthCategoryFilterEndToEnd confirms the ?auth_category= query param actually
// filters the rendered auth-log rows, not just the pure bucketing function above.
func TestLogsAuthCategoryFilterEndToEnd(t *testing.T) {
	app := newTestApp(t)
	mux := app.Mux()
	cookie := loginSession(t, app)

	app.DB.LogAuthAttempt("admin_login", "someadmin", "203.0.113.1", false, "bad password")
	app.DB.LogAuthAttempt("sender", "someone@example.com", "203.0.113.2", false, "bad password")

	req := httptest.NewRequest(http.MethodGet, Prefix+"/logs?type=auth&auth_category=mailserver", nil)
	req.AddCookie(cookie)
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status=%d", rec.Code)
	}
	body := rec.Body.String()
	if !strings.Contains(body, "someone@example.com") {
		t.Error("mailserver category should include the sender auth failure")
	}
	if strings.Contains(body, "someadmin") {
		t.Error("mailserver category should exclude the admin_login failure")
	}
}
