package control

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

func TestTaskCatalogSeparatesCollectionFromExecution(t *testing.T) {
	o := testOperations(t)
	now := time.Now().UTC()
	b := testBatch("failed", now)
	if err := o.CommitBatch(context.Background(), b); err != nil {
		t.Fatal(err)
	}
	for _, stale := range []bool{false, true} {
		at := now
		if stale {
			at = at.Add(4 * time.Minute)
		}
		items, err := o.TaskViews(context.Background(), at)
		if err != nil {
			t.Fatal(err)
		}
		for _, task := range items {
			if task.Key == "salesforce_org" {
				expect := "partial"
				if stale {
					expect = "unknown"
				}
				if task.Collection.Status != expect || task.LatestRun == nil || task.LatestRun.Status != "failed" || task.CanRun {
					t.Fatal("collection freshness hid failure or enabled unsafe action")
				}
			}
			if task.Key == "salesforce_account" && task.LatestRun != nil {
				t.Fatal("shared provider run attributed to wrong task")
			}
			if task.Key == "dbt_billing" && task.Coverage != "unconfigured" {
				t.Fatal("missing provider treated as observed")
			}
		}
	}
}
