package safego

import (
	"sync"
	"testing"
)

// TestGo_RecoversPanic is the concrete proof for the B1 fix in
// plans/2026-07-11-nomos-agent-code-review.md: a panic inside a goroutine
// launched via Go must not crash the process (or, here, the test binary —
// the same guarantee). Before this package existed, every background
// goroutine in cmd/nomos/internal/mcp/internal/httpapi used a bare `go`
// statement; an unhandled panic in any of them takes down the entire Go
// process, not just that goroutine.
func TestGo_RecoversPanic(t *testing.T) {
	var wg sync.WaitGroup
	wg.Add(1)

	Go("test:deliberate-panic", func() {
		defer wg.Done()
		panic("this must be recovered, not crash the test binary")
	})

	// If the panic weren't recovered, the whole test binary would crash
	// before ever reaching this line (a Go panic in any goroutine terminates
	// the process, full stop) — Wait() returning normally IS the proof.
	wg.Wait()
}

// TestGo_RunsFnNormally confirms the non-panic path still just runs fn.
func TestGo_RunsFnNormally(t *testing.T) {
	done := make(chan bool, 1)
	Go("test:normal", func() {
		done <- true
	})
	if !<-done {
		t.Fatal("fn did not run")
	}
}
