package webui

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

	"mailgoserver/internal/db"
	"mailgoserver/internal/mailstore"
)

// TestDashboardShowsMailboxNearQuota confirms the dashboard tile surfaces a mailbox
// that has crossed the 90% quota threshold, and doesn't for one that hasn't.
func TestDashboardShowsMailboxNearQuota(t *testing.T) {
	app := newTestApp(t)
	mux := app.Mux()
	cookie := loginSession(t, app) // global admin

	domains, err := app.DB.ListDomains()
	if err != nil || len(domains) == 0 {
		t.Fatalf("expected a seeded domain: %v", err)
	}
	domainID := domains[0].ID

	dek := mailstore.GenerateDEK()
	wrapped, nonce, err := app.Mailstore.WrapDEK(dek)
	if err != nil {
		t.Fatal(err)
	}
	hash, err := db.HashPassword("irrelevant-portal-password")
	if err != nil {
		t.Fatal(err)
	}
	fullID, err := app.DB.CreateMailbox("full@example.com", hash, domainID, 100, wrapped, nonce)
	if err != nil {
		t.Fatal(err)
	}
	if err := app.DB.AddMailboxUsedBytes(fullID, 95); err != nil { // 95% full
		t.Fatal(err)
	}

	req := httptest.NewRequest(http.MethodGet, Prefix+"/", nil)
	req.AddCookie(cookie)
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("dashboard status = %d", rec.Code)
	}
	if !strings.Contains(rec.Body.String(), "near quota") {
		t.Fatal("expected the dashboard to flag a mailbox at 95% quota usage")
	}
}
