package tun

import (
	"bytes"
	"context"
	"sync"
	"testing"
	"time"

	"github.com/xtls/xray-core/common/buf"
	"github.com/xtls/xray-core/common/net"
	"github.com/xtls/xray-core/common/protocol"
	"github.com/xtls/xray-core/proxy/vless/encoding"
)

func nextUDPTestConn(t *testing.T, c <-chan *udpConn) *udpConn {
	t.Helper()
	select {
	case v := <-c:
		return v
	case <-time.After(time.Second):
		t.Fatal("missing UDP association")
		return nil
	}
}
func TestTivraFixedDestinationUDPAssociations(t *testing.T) {
	for _, test := range []struct {
		name, first, second string
		port                net.Port
	}{
		{"dns-v4", "1.1.1.1", "9.9.9.9", 53}, {"quic-v4", "1.1.1.1", "9.9.9.9", 443},
		{"dns-v6", "2606:4700:4700::1111", "2620:fe::fe", 53}, {"quic-v6", "2606:4700:4700::1111", "2620:fe::fe", 443},
	} {
		t.Run(test.name, func(t *testing.T) {
			connections := make(chan *udpConn, 4)
			responseSources := make(chan net.Destination, 4)
			handler := newUdpConnectionHandler(func(c net.Conn, _ net.Destination) { connections <- c.(*udpConn) }, func(_ []byte, src, dst net.Destination) error { responseSources <- src; return nil })
			source := net.UDPDestination(net.ParseAddress("198.18.0.1"), 40000)
			targets := []net.Destination{net.UDPDestination(net.ParseAddress(test.first), test.port), net.UDPDestination(net.ParseAddress(test.second), test.port)}
			for _, target := range targets {
				handler.HandlePacket(source, target, []byte("query"))
			}
			seen := map[net.Destination]bool{}
			for range targets {
				c := nextUDPTestConn(t, connections)
				defer c.Close()
				seen[c.dst] = true
				mb, err := c.ReadMultiBuffer()
				if err != nil || mb[0].UDP == nil || *mb[0].UDP != c.dst {
					t.Fatal("wrong packet destination")
				}
				// The actual plain VLESS encoder drops per-packet address metadata;
				// each native association must already carry the correct target.
				request := &protocol.RequestHeader{Command: protocol.RequestCommandUDP, Address: c.dst.Address, Port: c.dst.Port}
				var wire bytes.Buffer
				writer := encoding.EncodeBodyAddons(buf.NewWriter(&wire), request, &encoding.Addons{}, nil, true, context.Background(), nil, nil)
				if err = writer.WriteMultiBuffer(mb); err != nil {
					t.Fatal(err)
				}
				reader := encoding.DecodeBodyAddons(bytes.NewReader(wire.Bytes()), request, &encoding.Addons{})
				response, err := reader.ReadMultiBuffer()
				if err != nil {
					t.Fatal(err)
				}
				if err = c.WriteMultiBuffer(response); err != nil {
					t.Fatal(err)
				}
				if <-responseSources != c.dst {
					t.Fatal("response source does not match intended target")
				}
			}
			if len(seen) != 2 || !seen[targets[0]] || !seen[targets[1]] {
				t.Fatal("different DNS/QUIC targets aliased")
			}
		})
	}
}
func TestTivraOtherUDPStillUsesFullConeAndPreservesPacketDestination(t *testing.T) {
	connections := make(chan *udpConn, 4)
	handler := newUdpConnectionHandler(func(c net.Conn, _ net.Destination) { connections <- c.(*udpConn) }, func([]byte, net.Destination, net.Destination) error { return nil })
	source := net.UDPDestination(net.ParseAddress("198.18.0.1"), 40000)
	first := net.UDPDestination(net.ParseAddress("1.1.1.1"), 3478)
	second := net.UDPDestination(net.ParseAddress("9.9.9.9"), 9999)
	handler.HandlePacket(source, first, []byte("one"))
	c := nextUDPTestConn(t, connections)
	defer c.Close()
	handler.HandlePacket(source, second, []byte("two"))
	handler.RLock()
	count := len(handler.udpConns)
	handler.RUnlock()
	if count != 1 {
		t.Fatal("ordinary FullCone partition changed")
	}
	for _, want := range []net.Destination{first, second} {
		mb, err := c.ReadMultiBuffer()
		if err != nil || mb[0].UDP == nil || *mb[0].UDP != want {
			t.Fatal("packet target lost")
		}
		buf.ReleaseMulti(mb)
	}
}
func TestTivraUDPKeysAndDoubleCloseDoNotDeleteOtherAssociations(t *testing.T) {
	connections := make(chan *udpConn, 8)
	handler := newUdpConnectionHandler(func(c net.Conn, _ net.Destination) { connections <- c.(*udpConn) }, func([]byte, net.Destination, net.Destination) error { return nil })
	source := net.UDPDestination(net.ParseAddress("198.18.0.1"), 40000)
	first := net.UDPDestination(net.ParseAddress("1.1.1.1"), 53)
	other := net.UDPDestination(net.ParseAddress("9.9.9.9"), 53)
	handler.HandlePacket(source, first, []byte("a"))
	old := nextUDPTestConn(t, connections)
	handler.HandlePacket(source, other, []byte("b"))
	second := nextUDPTestConn(t, connections)
	defer second.Close()
	old.Close()
	handler.HandlePacket(source, first, []byte("c"))
	replacement := nextUDPTestConn(t, connections)
	defer replacement.Close()
	old.Close()
	handler.RLock()
	defer handler.RUnlock()
	if handler.udpConns[associationKey(source, first)] != replacement || handler.udpConns[associationKey(source, other)] != second {
		t.Fatal("old close removed replacement or other destination")
	}
	if associationKey(source, first) == associationKey(net.UDPDestination(source.Address, 40001), first) {
		t.Fatal("source ports alias")
	}
	if associationKey(source, first) == associationKey(source, net.UDPDestination(first.Address, 443)) {
		t.Fatal("DNS and QUIC alias")
	}
}
func TestTivraUDPConcurrentHandleAndClose(t *testing.T) {
	var callbacks sync.WaitGroup
	handler := newUdpConnectionHandler(func(c net.Conn, _ net.Destination) { defer callbacks.Done(); c.Close(); c.Close() }, func([]byte, net.Destination, net.Destination) error { return nil })
	// Count handler creation in the callback-free wrapper to avoid WaitGroup Add
	// racing Wait: wait only after all HandlePacket callers have completed.
	original := handler.handleConnection
	handler.handleConnection = func(c net.Conn, d net.Destination) { callbacks.Add(1); original(c, d) }
	var writers sync.WaitGroup
	for worker := 0; worker < 8; worker++ {
		writers.Add(1)
		go func(worker int) {
			defer writers.Done()
			for i := 0; i < 100; i++ {
				source := net.UDPDestination(net.ParseAddress("198.18.0.1"), net.Port(40000+worker))
				target := net.UDPDestination(net.ParseAddress("1.1.1.1"), net.Port(53+(i%2)*390))
				handler.HandlePacket(source, target, []byte("q"))
			}
		}(worker)
	}
	writers.Wait()
	// Map must settle empty; this also waits for callbacks not yet scheduled.
	waitReaderTest(t, func() bool { handler.RLock(); defer handler.RUnlock(); return len(handler.udpConns) == 0 })
	callbacks.Wait()
}
