package webui

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

// TestAdminRulesAddMultiConditionAndRenders confirms the admin-side rule builder
// (mirroring the self-service one) accepts a multi-condition submission and that the
// rules list page actually renders it (ruleSummary executes correctly at runtime,
// not just parses at template-load time).
func TestAdminRulesAddMultiConditionAndRenders(t *testing.T) {
	app := newTestApp(t)
	mux := app.Mux()
	cookie := loginSession(t, app)
	domains, _ := app.DB.ListDomains()
	mbox := createMailboxFor(t, app, "adminruler@example.com", domains[0].ID)

	form := url.Values{
		"priority":        {"0"},
		"match_type":      {"all"},
		"condition_field": {"to", "subject"},
		"condition_op":    {"contains", "contains"},
		"condition_value": {"sales", "invoice"},
		"action":          {"mark_as_spam"},
		"action_value":    {""},
	}
	addReq := httptest.NewRequest(http.MethodPost, Prefix+"/mailboxes/"+strconv.FormatInt(mbox.ID, 10)+"/rules/add", strings.NewReader(form.Encode()))
	addReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	addReq.AddCookie(cookie)
	addRec := httptest.NewRecorder()
	mux.ServeHTTP(addRec, addReq)
	if addRec.Code != http.StatusFound {
		t.Fatalf("add rule: status=%d body=%s", addRec.Code, addRec.Body.String())
	}

	listReq := httptest.NewRequest(http.MethodGet, Prefix+"/mailboxes/"+strconv.FormatInt(mbox.ID, 10)+"/rules", nil)
	listReq.AddCookie(cookie)
	listRec := httptest.NewRecorder()
	mux.ServeHTTP(listRec, listReq)
	if listRec.Code != http.StatusOK {
		t.Fatalf("rules list: status=%d body=%s", listRec.Code, listRec.Body.String())
	}
	body := listRec.Body.String()
	if !strings.Contains(body, "to contains &#34;sales&#34;") || !strings.Contains(body, "AND") {
		t.Fatalf("expected the rendered condition summary to show both AND'd conditions, got: %s", body)
	}
	if !strings.Contains(body, "Mark as Junk") {
		t.Fatal("expected the mark_as_spam action to render")
	}
}
