package main

import (
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func TestSourceTerminalClosureRequestsOrderlyShutdown(t *testing.T) {
	a := newLauncher(t.TempDir(), t.TempDir(), "token")
	r, w := io.Pipe()
	defer r.Close()
	defer w.Close()
	done := make(chan struct{})
	go func() { a.watchSourceParent(r); close(done) }()
	if _, err := io.WriteString(w, "terminal still open"); err != nil {
		t.Fatal(err)
	}
	if a.stopping() {
		t.Fatal("terminal input stopped the application before EOF")
	}
	_ = w.Close()
	select {
	case <-done:
	case <-time.After(time.Second):
		t.Fatal("closing the terminal did not request shutdown")
	}
	if !a.stopping() {
		t.Fatal("source parent EOF must follow the normal shutdown path")
	}
	// A browser close request racing with parent EOF must remain idempotent.
	a.watchSourceParent(strings.NewReader(""))
}

func TestSourceClosePageExplainsHowToRestartFromSource(t *testing.T) {
	t.Setenv("CHATLOOP_SOURCE_PARENT", "1")
	a := newLauncher(t.TempDir(), t.TempDir(), "token")
	r := httptest.NewRequest(http.MethodPost, "http://"+controlAddress+"/stop", strings.NewReader("csrf=token"))
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Set("Origin", "http://"+controlAddress)
	w := httptest.NewRecorder()
	a.stopServer(w, r)
	if w.Code != 200 || !strings.Contains(w.Body.String(), "npm.cmd start") || strings.Contains(w.Body.String(), "ChatLoop.exe") {
		t.Fatal("source users were instructed to reopen a distributed executable")
	}
}
