package main

import (
	"bytes"
	"runtime"
	"runtime/pprof"
	"strings"
	"testing"
	"time"
)

// section: test
func TestGoroutineLeakDetection(t *testing.T) {
	prof := pprof.Lookup("goroutineleak")
	if prof == nil {
		t.Skip("goroutineleak profile not available - build with GOEXPERIMENT=goroutineleakprofile")
	}

	// Create a leak - goroutine blocked on unbuffered channel
	ch := make(chan int)
	go func() {
		ch <- 1 // Will block forever - no receiver
	}()

	// Force GC to identify leaked goroutines
	runtime.GC()
	time.Sleep(100 * time.Millisecond)

	var buf bytes.Buffer
	prof.WriteTo(&buf, 2) // 2 = full stack traces

	if strings.Contains(buf.String(), "(leaked)") {
		t.Log("Leak detected (expected):")
		t.Log(buf.String())
	}
}

// section: test

// section: check
func checkForLeaks(t *testing.T) {
	t.Helper()

	prof := pprof.Lookup("goroutineleak")
	if prof == nil {
		return // Profile not available
	}

	runtime.GC()
	time.Sleep(50 * time.Millisecond)

	var buf bytes.Buffer
	prof.WriteTo(&buf, 2)

	if strings.Contains(buf.String(), "(leaked)") {
		t.Error("Goroutine leak detected!")
		t.Log(buf.String())
	}
}

// section: check
