package smtpserver

import (
	"net/smtp"
	"testing"
)

// TestRepeatedFailedAuthBlacklistsIP is the live-flow check for the abuseguard wiring
// (see auth.go's authenticate): enough real failed AUTH PLAIN attempts over real TCP
// against a real smtpserver.Backend should land the source IP in esrv_ip_blacklist,
// exactly as internal/abuseguard's own unit tests confirm in isolation — this confirms
// the actual auth.go call site is wired up, not just the abuseguard package itself.
func TestRepeatedFailedAuthBlacklistsIP(t *testing.T) {
	backend := newTestBackend(t)
	sec, _ := backend.Cfg.NewSection("Security")
	sec.NewKey("abuse_detection_enabled", "true")
	sec.NewKey("abuse_failure_threshold", "3")
	sec.NewKey("abuse_detection_window_minutes", "10")
	sec.NewKey("abuse_blacklist_base_hours", "12")
	sec.NewKey("abuse_blacklist_max_hours", "168")

	addr := startTestServer(t, backend)

	for i := 0; i < 3; i++ {
		c, err := smtp.Dial(addr)
		if err != nil {
			t.Fatal(err)
		}
		if authErr := c.Auth(smtp.PlainAuth("", "test@example.com", "wrongpassword", "127.0.0.1")); authErr == nil {
			t.Fatal("expected auth failure")
		}
		c.Close()
	}

	blocked, err := backend.DB.IsIPBlacklisted("127.0.0.1")
	if err != nil {
		t.Fatal(err)
	}
	if !blocked {
		t.Fatal("expected 127.0.0.1 to be blacklisted after 3 failed AUTH attempts (threshold=3)")
	}
}
