package udp

import (
	"bytes"
	"testing"
)

// Bytes captured from a real W&P relay in front of MSHV: the origin as text,
// a '|', then the untouched WSJT-X packet. This exact datagram produced
// "bad magic 0x3132372e" — 0x3132372e being ASCII "127.".
var wpDecode = []byte{
	// "127.0.0.1:2237|"
	0x31, 0x32, 0x37, 0x2e, 0x30, 0x2e, 0x30, 0x2e, 0x31, 0x3a, 0x32, 0x32, 0x33, 0x37, 0x7c,
	// magic, schema 3, type 2 (Decode), id "MSHV"
	0xad, 0xbc, 0xcb, 0xda, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02,
	0x00, 0x00, 0x00, 0x04, 0x4d, 0x53, 0x48, 0x56,
	0x01, 0x01, 0x4b, 0x31, 0x28, 0x00, 0x00, 0x00, 0x16,
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x8a,
	0x00, 0x00, 0x00, 0x03, 0x46, 0x54, 0x38, // "FT8"
	0x00, 0x00, 0x00, 0x0e, 0x54, 0x4e, 0x38, 0x47, 0x44, 0x20, 0x39, 0x41, 0x31, 0x4d, 0x4d, 0x20, 0x37, 0x33, // "TN8GD 9A1MM 73"
	0x00, 0x00,
}

func TestParseWSJTBehindAForwarder(t *testing.T) {
	if _, _, err := ParseWSJT(wpDecode); err != nil {
		t.Fatalf("relayed packet still fails: %v", err)
	}
	// And the header is what was in the way: without it the same bytes parse.
	if _, _, err := ParseWSJT(wpDecode[15:]); err != nil {
		t.Fatalf("bare packet fails: %v", err)
	}
}

func TestStripForwarderHeader(t *testing.T) {
	bare := wpDecode[15:]

	if got := stripForwarderHeader(bare); !bytes.Equal(got, bare) {
		t.Error("a packet with no header must be returned untouched")
	}
	if got := stripForwarderHeader(wpDecode); !bytes.Equal(got, bare) {
		t.Error("the text header was not stripped")
	}

	// A BINARY prefix is not a forwarder header — refusing it is what stops a
	// corrupt packet that merely contains the magic from becoming a QSO.
	binPrefix := append([]byte{0x00, 0x01, 0x02}, bare...)
	if got := stripForwarderHeader(binPrefix); !bytes.Equal(got, binPrefix) {
		t.Error("a non-printable prefix must not be treated as a header")
	}

	// Beyond the window, the magic is ignored however printable the prefix is.
	far := append(bytes.Repeat([]byte("A"), maxFwdHeader+1), bare...)
	if got := stripForwarderHeader(far); !bytes.Equal(got, far) {
		t.Error("magic past maxFwdHeader must not be trusted")
	}

	// No magic anywhere, and runt packets, must not panic or invent anything.
	for _, junk := range [][]byte{[]byte("127.0.0.1:2237|hello"), {}, {0xad}, {0xad, 0xbc, 0xcb}} {
		if got := stripForwarderHeader(junk); !bytes.Equal(got, junk) {
			t.Errorf("junk %q was altered", junk)
		}
	}
}
