package udp

import (
	"encoding/binary"
	"testing"
)

// An operator's log arrived with four hundred identical "ADIF payload ignored"
// lines and nothing else legible: two inbound listeners were configured on the
// SAME multicast group and port, one WSJT and one ADIF, so every WSJT-X decode
// was delivered to both and the ADIF one rejected each in writing. An FT8 cycle
// is dozens of decodes every fifteen seconds.
//
// The listener has to recognise that traffic and say what it is — once.
func TestIgnoredADIFStaysBounded(t *testing.T) {
	s := &Server{cfg: Config{Name: "FLDIGI", Port: 2237}}

	// A WSJT-X packet: magic first. One line is the whole diagnosis, so the
	// counter is pushed past the cap immediately.
	pkt := make([]byte, 16)
	binary.BigEndian.PutUint32(pkt[:4], wsjtMagic)
	s.noteIgnoredADIF(pkt)
	if s.badPkts <= maxBadPktDumps {
		t.Errorf("badPkts = %d — WSJT traffic should silence the listener at once", s.badPkts)
	}

	// Anything else is described a few times before going quiet, so an ordinary
	// keep-alive does not get the same one-line treatment as a real diagnosis.
	s2 := &Server{cfg: Config{Name: "FLDIGI", Port: 2237}}
	s2.noteIgnoredADIF([]byte("keep-alive"))
	if s2.badPkts > maxBadPktDumps {
		t.Errorf("one unusable payload silenced the listener (badPkts = %d)", s2.badPkts)
	}
	for i := 0; i < 50; i++ {
		s2.noteIgnoredADIF([]byte("keep-alive"))
	}
	if s2.badPkts <= maxBadPktDumps {
		t.Errorf("badPkts = %d — the throttle never engaged", s2.badPkts)
	}
}
