package src_test

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

// section: test
func Test_WithContext(t *testing.T) {
	// Create a test server that uses the request context
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		// Simulate work that respects context cancellation
		select {
		case <-time.After(100 * time.Millisecond):
			w.WriteHeader(http.StatusOK)
		case <-ctx.Done():
			w.WriteHeader(http.StatusServiceUnavailable)
		}
	})

	server := httptest.NewServer(handler)
	t.Cleanup(server.Close)

	// Use t.Context() - automatically canceled when test completes
	ctx := t.Context()

	req, err := http.NewRequestWithContext(ctx, "GET", server.URL, nil)
	if err != nil {
		t.Fatal(err)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		t.Errorf("expected status 200, got %d", resp.StatusCode)
	}

	t.Log("Request completed successfully with test context")
}

// section: test

// section: cancel
func Test_ContextCancellation(t *testing.T) {
	ctx := t.Context()

	// Start a goroutine that will be canceled when test ends
	done := make(chan struct{})
	go func() {
		<-ctx.Done()
		close(done)
	}()

	t.Log("Test completing - context will be canceled")
	// The goroutine above will be automatically cleaned up
	// when the test function returns and ctx is canceled
}

// section: cancel

// Helper function to demonstrate context usage
func doWorkWithContext(ctx context.Context) error {
	select {
	case <-time.After(50 * time.Millisecond):
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}
