//go:build darwin

package libXray

import (
	"fmt"
	"os"
	"testing"
	"time"
)

// A pipe supplies the same borrowed-descriptor API used by iOS without creating
// a system VPN or making any network request. Closing its writer gives the real
// DarwinTun read path an EOF, not an invented wrapper snapshot.
func TestInvokeRealDarwinTUNReaderFailureAndReplacement(t *testing.T) {
	t.Setenv("xray.tun.fd", "")
	t.Cleanup(func() { _ = invokeForTest(t, LibXrayMethodStopXray, nil) })
	for attempt := 0; attempt < 2; attempt++ {
		read, write, err := os.Pipe()
		if err != nil {
			t.Fatal(err)
		}
		config := fmt.Sprintf(`{"env":{"xray.tun.fd":"%d"},"log":{"loglevel":"none"},"inbounds":[{"tag":"tivra-tun","protocol":"tun","port":0,"settings":{"name":"utun","mtu":1280}}],"outbounds":[{"protocol":"blackhole"}]}`, read.Fd())
		response := invokeForTest(t, LibXrayMethodRunXray, RunXrayRequest{XrayJson: config})
		if !response.Success {
			read.Close()
			write.Close()
			t.Fatalf("start: %s", response.Err)
		}
		state := decodeDataObject[GetXrayStateResponse](t, invokeForTest(t, LibXrayMethodGetXrayState, nil))
		if !state.Running || state.TUNReaders["tivra-tun"].State != "running" {
			t.Fatalf("replacement did not start clean: %+v", state)
		}
		write.Close()
		deadline := time.Now().Add(2 * time.Second)
		for {
			state = decodeDataObject[GetXrayStateResponse](t, invokeForTest(t, LibXrayMethodGetXrayState, nil))
			if state.TUNReaders["tivra-tun"].State == "failed" {
				break
			}
			if time.Now().After(deadline) {
				t.Fatalf("real TUN EOF never surfaced: %+v", state)
			}
			time.Sleep(time.Millisecond)
		}
		if !state.Running || state.TUNReaders["tivra-tun"].ErrorKind != "eof" {
			t.Fatalf("wrong local fault state %+v", state)
		}
		response = invokeForTest(t, LibXrayMethodStopXray, nil)
		if !response.Success {
			t.Fatal(response.Err)
		}
		state = decodeDataObject[GetXrayStateResponse](t, invokeForTest(t, LibXrayMethodGetXrayState, nil))
		if state.Running || len(state.TUNReaders) > 0 {
			t.Fatal("stopped snapshot retained failure")
		}
		if _, err = read.Stat(); err != nil {
			t.Fatal("core closed caller-owned input descriptor")
		}
		read.Close()
	}
}
