package main

import (
	"net"
	"os"
	"testing"
)

// TestIsCharDeviceRejectsNonConsoles pins down the half of the check that can
// be tested without a terminal: a pipe, a regular file and a closed handle
// must all read as "not a console", because each of them means something other
// than a person waiting at a keyboard.
//
// Getting this wrong in this direction is the dangerous one: it would drop a
// script or a build pipeline into an interactive prompt and hang it forever.
func TestIsCharDeviceRejectsNonConsoles(t *testing.T) {
	r, w, err := os.Pipe()
	if err != nil {
		t.Fatalf("pipe: %v", err)
	}
	defer r.Close()
	defer w.Close()

	tmp, err := os.CreateTemp(t.TempDir(), "out")
	if err != nil {
		t.Fatalf("temp file: %v", err)
	}
	defer tmp.Close()

	devNull, err := os.Open(os.DevNull)
	if err != nil {
		t.Fatalf("open %s: %v", os.DevNull, err)
	}
	defer devNull.Close()

	for _, tc := range []struct {
		name string
		file *os.File
		want bool
	}{
		{"read end of a pipe", r, false},
		{"write end of a pipe", w, false},
		{"regular file", tmp, false},
		// os.DevNull IS a character device on Unix, so this case documents a
		// real limitation rather than asserting a value that differs by
		// platform: `prog < /dev/null` on Unix looks interactive on stdin.
		// It is harmless, because stdout must ALSO be a console, and a script
		// redirecting stdin almost always redirects stdout too.
	} {
		if got := isCharDevice(tc.file); got != tc.want {
			t.Errorf("isCharDevice(%s) = %v, want %v", tc.name, got, tc.want)
		}
	}
	_ = devNull
}

// TestIsCharDeviceHandlesAClosedFile makes sure a handle we cannot stat is
// treated as "not a console" rather than panicking or defaulting to true.
func TestIsCharDeviceHandlesAClosedFile(t *testing.T) {
	f, err := os.CreateTemp(t.TempDir(), "closed")
	if err != nil {
		t.Fatalf("temp file: %v", err)
	}
	f.Close()
	if isCharDevice(f) {
		t.Error("isCharDevice(closed file) = true, want false")
	}
}

// TestInteractiveConsoleNeedsBothEnds asserts the AND: one console end is not
// enough. Under `go test` stdout is not a terminal, so this must be false.
func TestInteractiveConsoleNeedsBothEnds(t *testing.T) {
	if interactiveConsole() {
		t.Error("interactiveConsole() = true under `go test`, where output is captured; " +
			"the guided prompt would hang any non-interactive run")
	}
}

// TestDefaultTargetIsUsable guards the one-keypress default. OpsTunnel asks for
// an address rather than a folder, so the equivalent guarantee is that pressing
// Enter produces something "check" will accept — otherwise the reader's very
// first interaction is an error message about their own default.
func TestDefaultTargetIsUsable(t *testing.T) {
	if why := badTarget(defaultTarget); why != "" {
		t.Fatalf("defaultTarget = %q is rejected by the prompt itself: %s", defaultTarget, why)
	}
	if _, _, err := net.SplitHostPort(defaultTarget); err != nil {
		t.Errorf("defaultTarget = %q is not host:port: %v", defaultTarget, err)
	}
}

// TestBadTargetExplainsInsteadOfLeakingGoErrors checks the retry loop's
// messages: every rejection must be a sentence a person can act on, and a good
// address must not be rejected.
func TestBadTargetExplainsInsteadOfLeakingGoErrors(t *testing.T) {
	for _, tc := range []struct {
		in       string
		rejected bool
	}{
		{"127.0.0.1:445", false},
		{"fileserver:22", false},
		{"[::1]:8080", false},
		{"127.0.0.1", true},  // no port at all
		{":22", true},        // no machine
		{"host:ssh", true},   // port must be a number
		{"host:70000", true}, // out of range
		{"host:0", true},     // out of range
	} {
		why := badTarget(tc.in)
		if tc.rejected && why == "" {
			t.Errorf("badTarget(%q) accepted an address check cannot dial", tc.in)
		}
		if !tc.rejected && why != "" {
			t.Errorf("badTarget(%q) = %q, want accepted", tc.in, why)
		}
	}
}
