package webui

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
)

// TestWebmailRecipientSuggest confirms the autocomplete endpoint returns addresses
// this mailbox has actually exchanged mail with (Sent "To" + INBOX "From"), matching
// the query fragment, and nothing for an empty query.
func TestWebmailRecipientSuggest(t *testing.T) {
	app := newTestApp(t)
	mux := app.Mux()
	domains, _ := app.DB.ListDomains()
	mailboxID := createTestMailboxWithPassword(t, app, "autocomplete@example.com", domains[0].ID, "autocomplete-password-1!")
	cookie := webmailLoginSession(t, app, mailboxID)

	sentRaw := "From: autocomplete@example.com\r\nTo: alice@example.com\r\nSubject: hi\r\n\r\nbody"
	if _, err := app.Mailstore.StoreMessage(mailboxID, "Sent", []byte(sentRaw), "s1@example.com", "autocomplete@example.com", "hi"); err != nil {
		t.Fatal(err)
	}
	inboxRaw := "From: bob@example.com\r\nTo: autocomplete@example.com\r\nSubject: hey\r\n\r\nbody"
	if _, err := app.Mailstore.StoreMessage(mailboxID, "INBOX", []byte(inboxRaw), "i1@example.com", "bob@example.com", "hey"); err != nil {
		t.Fatal(err)
	}

	get := func(q string) []string {
		req := httptest.NewRequest(http.MethodGet, MailboxPrefix+"/mail/recipients?q="+q, nil)
		req.AddCookie(cookie)
		rec := httptest.NewRecorder()
		mux.ServeHTTP(rec, req)
		if rec.Code != http.StatusOK {
			t.Fatalf("status=%d", rec.Code)
		}
		var out []string
		if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
			t.Fatalf("decode: %v body=%s", err, rec.Body.String())
		}
		return out
	}

	aliceMatches := get("alice")
	if len(aliceMatches) != 1 || aliceMatches[0] != "alice@example.com" {
		t.Fatalf("expected alice@example.com from Sent history, got %v", aliceMatches)
	}
	bobMatches := get("bob")
	if len(bobMatches) != 1 || bobMatches[0] != "bob@example.com" {
		t.Fatalf("expected bob@example.com from INBOX history, got %v", bobMatches)
	}
	if none := get(""); len(none) != 0 {
		t.Fatalf("expected no suggestions for an empty query, got %v", none)
	}
	if none := get("nobody-like-this"); len(none) != 0 {
		t.Fatalf("expected no suggestions for a non-matching query, got %v", none)
	}
}
