package peer

import (
	"crypto/rand"
	"net/netip"
	"reflect"
	"testing"
)

func TestSynPacket(t *testing.T) {
	p := packetSyn{
		TraceID: 2342342345,
		Direct:  true,
	}
	rand.Read(p.SharedKey[:])

	p.PossibleAddrs[0] = netip.AddrPortFrom(netip.AddrFrom4([4]byte{1, 2, 3, 4}), 234)
	p.PossibleAddrs[1] = netip.AddrPortFrom(netip.AddrFrom4([4]byte{2, 2, 3, 4}), 12399)
	p.PossibleAddrs[2] = netip.AddrPortFrom(netip.AddrFrom4([4]byte{3, 2, 3, 4}), 60000)

	buf := p.Marshal(newBuf())
	p2, err := parsePacketSyn(buf)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(p, p2) {
		t.Fatal(p2)
	}
}

func TestAckPacket(t *testing.T) {
	p := packetAck{
		TraceID: 123213,
		ToAddr:  netip.AddrPortFrom(netip.AddrFrom4([4]byte{1, 2, 3, 4}), 234),
	}

	p.PossibleAddrs[0] = netip.AddrPortFrom(netip.AddrFrom4([4]byte{8, 2, 3, 4}), 100)
	p.PossibleAddrs[1] = netip.AddrPortFrom(netip.AddrFrom4([4]byte{2, 2, 3, 4}), 12399)
	p.PossibleAddrs[2] = netip.AddrPortFrom(netip.AddrFrom4([4]byte{3, 2, 3, 4}), 60000)

	buf := p.Marshal(newBuf())
	p2, err := parsePacketAck(buf)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(p, p2) {
		t.Fatal(p2)
	}
}

func TestProbePacket(t *testing.T) {
	p := packetProbe{
		TraceID: 12345,
	}

	buf := p.Marshal(newBuf())
	p2, err := parsePacketProbe(buf)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(p, p2) {
		t.Fatal(p2)
	}
}
