package automation

import (
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
)

func TestSchedulerBackgroundContextsUseNamedHelpers(t *testing.T) {
	src := readAutomationSourceForSchedulerContextStructure(t, "scheduler_service.go")

	if count := strings.Count(src, "context.Background()"); count != 1 {
		t.Fatalf("scheduler_service.go context.Background() count = %d, want 1 helper-owned call", count)
	}
	for _, forbidden := range []string{
		"constants.WithSecurityContext(context.Background(), constants.SystemContext, \"flow interview resume\")",
		"ctx := context.Background()",
	} {
		if strings.Contains(src, forbidden) {
			t.Fatalf("scheduler_service.go still owns raw background context fragment %q", forbidden)
		}
	}
	for _, symbol := range []string{
		"func (s *SchedulerService) RunWorkerRole(ctx context.Context) error",
		"ctx := s.schedulerControllerContext()",
		"context.WithoutCancel(ctx)",
		"s.startScheduler(schedulerDetachedContext(), true, true)",
		"func schedulerDetachedContext() context.Context",
		"return context.Background()",
	} {
		if !strings.Contains(src, symbol) {
			t.Fatalf("scheduler_service.go is missing scheduler context fragment %q", symbol)
		}
	}
}

func readAutomationSourceForSchedulerContextStructure(t *testing.T, filename string) string {
	t.Helper()

	_, here, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("runtime.Caller failed")
	}
	raw, err := os.ReadFile(filepath.Join(filepath.Dir(here), filename))
	if err != nil {
		t.Fatalf("read %s: %v", filename, err)
	}
	return string(raw)
}
