package webui

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

// TestWebmailReadSignedMessageShowsBadgeAndCapturesContact confirms opening a signed
// message shows the verified badge and auto-adds the signer's certificate as a
// contact, matching how a real mail client behaves on a good signature.
func TestWebmailReadSignedMessageShowsBadgeAndCapturesContact(t *testing.T) {
	app := newTestApp(t)
	mux := app.Mux()
	domains, _ := app.DB.ListDomains()
	domainID := domains[0].ID

	senderID := createTestMailboxWithPassword(t, app, "read-signer@example.com", domainID, "signer-password-1!")
	recipientID := createTestMailboxWithPassword(t, app, "read-signee@example.com", domainID, "signee-password-1!")
	genIdentity(t, app, senderID, "read-signer@example.com")

	// No contact on file yet for the recipient — this is what auto-capture should fix.
	if contacts, _ := app.DB.ListSMIMEContacts(recipientID); len(contacts) != 0 {
		t.Fatalf("expected no contacts before reading, got %d", len(contacts))
	}

	senderCookie := webmailLoginSession(t, app, senderID)
	form := url.Values{
		"to": {"read-signee@example.com"}, "subject": {"Signed read test"}, "body_html": {"authentic content"},
		"smime_sign": {"1"},
	}
	req := httptest.NewRequest(http.MethodPost, MailboxPrefix+"/mail/compose", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(senderCookie)
	sendRec := httptest.NewRecorder()
	mux.ServeHTTP(sendRec, req)
	if sendRec.Code != http.StatusFound {
		t.Fatalf("compose send: status=%d body=%s", sendRec.Code, sendRec.Body.String())
	}

	msgs, err := app.DB.ListMessagesInFolder(recipientID, "INBOX")
	if err != nil || len(msgs) != 1 {
		t.Fatalf("expected 1 message, got %d (err=%v)", len(msgs), err)
	}

	// Reading a signed (but not encrypted) message needs no unlock at all — signature
	// verification only ever needs the signer's public certificate.
	recipientCookie := webmailLoginSession(t, app, recipientID)
	viewReq := httptest.NewRequest(http.MethodGet, MailboxPrefix+"/mail/INBOX/"+strconv.FormatInt(msgs[0].ID, 10), nil)
	viewReq.AddCookie(recipientCookie)
	viewRec := httptest.NewRecorder()
	mux.ServeHTTP(viewRec, viewReq)
	if viewRec.Code != http.StatusOK {
		t.Fatalf("view: status=%d body=%s", viewRec.Code, viewRec.Body.String())
	}
	body := viewRec.Body.String()
	if !strings.Contains(body, "Signature verified") {
		t.Fatalf("expected a verified-signature badge, got body: %s", body)
	}
	if !strings.Contains(body, "authentic content") {
		t.Fatal("expected the message body rendered after unwrapping the signature")
	}

	contacts, err := app.DB.ListSMIMEContacts(recipientID)
	if err != nil || len(contacts) != 1 || contacts[0].Email != "read-signer@example.com" {
		t.Fatalf("expected the signer auto-captured as a contact, got %+v (err=%v)", contacts, err)
	}
}
