package webui

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

// TestWebmailShortcutsPresentOnFolderAndMessageViews confirms the keyboard-shortcut
// script and the message-view button ids it hooks into are actually rendered, not
// just defined-but-never-invoked.
func TestWebmailShortcutsPresentOnFolderAndMessageViews(t *testing.T) {
	app := newTestApp(t)
	mux := app.Mux()
	domains, _ := app.DB.ListDomains()
	mailboxID := createTestMailboxWithPassword(t, app, "shortcuts@example.com", domains[0].ID, "shortcuts-password-1!")
	cookie := webmailLoginSession(t, app, mailboxID)
	uid := storeTestMessage(t, app, mailboxID, "INBOX", "someone@example.com", "hi", "body")

	folderReq := httptest.NewRequest(http.MethodGet, MailboxPrefix+"/mail/INBOX", nil)
	folderReq.AddCookie(cookie)
	folderRec := httptest.NewRecorder()
	mux.ServeHTTP(folderRec, folderReq)
	if !strings.Contains(folderRec.Body.String(), "msg-row-selected") {
		t.Fatalf("expected the shortcuts script rendered on the folder view, got: %s", folderRec.Body.String())
	}

	msgReq := httptest.NewRequest(http.MethodGet, MailboxPrefix+"/mail/INBOX/"+strconv.FormatInt(uid, 10), nil)
	msgReq.AddCookie(cookie)
	msgRec := httptest.NewRecorder()
	mux.ServeHTTP(msgRec, msgReq)
	msgBody := msgRec.Body.String()
	if !strings.Contains(msgBody, `id="replyBtn"`) || !strings.Contains(msgBody, "msg-row-selected") {
		t.Fatalf("expected both the reply button id and the shortcuts script on the message view, got: %s", msgBody)
	}
}
