package runner

import (
	"testing"
	"time"
)

func TestTaskCompletionWaitersAreBatchedAndSignaled(t *testing.T) {
	service := &Service{
		taskCompletionWaiters:  map[string]map[chan struct{}]struct{}{},
		taskCompletionPollWake: make(chan struct{}, 1),
	}
	first, unregisterFirst := service.registerTaskCompletionWaiter("task-1")
	defer unregisterFirst()
	second, unregisterSecond := service.registerTaskCompletionWaiter("task-2")

	taskIDs := service.taskCompletionWaiterIDs(10)
	if len(taskIDs) != 2 {
		t.Fatalf("batched task IDs=%v", taskIDs)
	}
	service.signalTaskCompletion("task-1")
	select {
	case <-first:
	case <-time.After(time.Second):
		t.Fatal("task completion waiter was not signaled")
	}
	select {
	case <-second:
		t.Fatal("unrelated task waiter was signaled")
	default:
	}

	unregisterSecond()
	if got := service.taskCompletionWaiterIDs(10); len(got) != 1 || got[0] != "task-1" {
		t.Fatalf("waiter unregister left unexpected IDs=%v", got)
	}
}

func TestTerminalTaskStatus(t *testing.T) {
	for _, status := range []string{"succeeded", "failed", "cancelled", "manual_review"} {
		if !terminalTaskStatus(status) {
			t.Fatalf("status %q should be terminal", status)
		}
	}
	for _, status := range []string{"queued", "running", "pending"} {
		if terminalTaskStatus(status) {
			t.Fatalf("status %q should not be terminal", status)
		}
	}
}
