package engine

import (
	"context"
	"testing"
	"time"
)

func TestBoundedWorkers(t *testing.T) {
	result, err := Run(context.Background(), Config{"fixed", 32, 3, 10, 0, 4})
	if err != nil || result.PeakActive > 3 || result.Completed != 24 || result.Failed != 8 || result.FinalActive != 0 {
		t.Fatalf("unexpected result: %+v, %v", result, err)
	}
}
func TestCancellationJoins(t *testing.T) {
	result, err := Run(context.Background(), Config{"fixed", 32, 3, 200, 30, 0})
	if err != nil || !result.Canceled || result.FinalActive != 0 || result.BlockedAtCancel != 0 || result.Completed != 0 {
		t.Fatalf("cancellation failed: %+v, %v", result, err)
	}
}
func TestBrokenModeExposesThenCleans(t *testing.T) {
	result, err := Run(context.Background(), Config{"broken", 12, 2, 200, 30, 0})
	if err != nil || result.PeakActive != 12 || result.BlockedAtCancel != 12 || result.FinalActive != 0 {
		t.Fatalf("teaching harness failed: %+v, %v", result, err)
	}
}
func TestCanceledParent(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	result, err := Run(ctx, Config{"fixed", 64, 8, 100, 0, 0})
	if err != nil || !result.Canceled || result.Started != 0 || result.FinalActive != 0 {
		t.Fatalf("parent ignored: %+v %v", result, err)
	}
}
func TestLimits(t *testing.T) {
	for _, config := range []Config{{"fixed", 0, 1, 10, 0, 0}, {"fixed", 65, 1, 10, 0, 0}, {"fixed", 1, 9, 10, 0, 0}, {"fixed", 1, 1, 1001, 0, 0}, {"other", 1, 1, 10, 0, 0}} {
		if _, err := Run(context.Background(), config); err == nil {
			t.Fatalf("accepted %+v", config)
		}
	}
}
func TestConcurrentRuns(t *testing.T) {
	for range 8 {
		t.Run("isolated", func(t *testing.T) {
			t.Parallel()
			result, err := Run(context.Background(), Config{"fixed", 12, 2, 10, 0, 0})
			if err != nil || result.Completed != 12 || result.FinalActive != 0 {
				t.Fatalf("%+v %v", result, err)
			}
		})
	}
}
func TestDeadline(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()
	r, e := Run(ctx, Config{"fixed", 64, 8, 1000, 0, 0})
	if e != nil || r.ElapsedMS > 500 || !r.Canceled {
		t.Fatalf("%+v %v", r, e)
	}
}
