package persistence

import (
	"testing"
)

func testRuntimeWorkOwnership() RuntimeWorkOwnership {
	return RuntimeWorkOwnership{
		WorkFamily:          "runtime.test-family.v1",
		DeploymentID:        "runtime-worker-test",
		WorkerReleaseDigest: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		OwnershipEpoch:      7,
	}
}

func TestRuntimeWorkOwnershipValidationIsGenericAndFailClosed(t *testing.T) {
	valid := testRuntimeWorkOwnership()
	for name, mutate := range map[string]func(*RuntimeWorkOwnership){
		"family":     func(o *RuntimeWorkOwnership) { o.WorkFamily = "audit/special" },
		"deployment": func(o *RuntimeWorkOwnership) { o.DeploymentID = "bad deployment" },
		"digest":     func(o *RuntimeWorkOwnership) { o.WorkerReleaseDigest = "not-a-digest" },
		"epoch":      func(o *RuntimeWorkOwnership) { o.OwnershipEpoch = 0 },
	} {
		t.Run(name, func(t *testing.T) {
			candidate := valid
			mutate(&candidate)
			if err := candidate.Validate(); err == nil {
				t.Fatalf("Validate(%+v) succeeded", candidate)
			}
		})
	}
	if err := valid.Validate(); err != nil {
		t.Fatal(err)
	}
}

func TestRuntimePoisonRepairRequiresCanonicalOperationIdentity(t *testing.T) {
	repair := RuntimePoisonRepair{
		RowID:                   "work-1",
		ExpectedRetryCount:      1,
		ExpectedLastErrorSHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
		RepairID:                "repair-1",
		Reason:                  "operator corrected the immutable input",
	}
	if err := repair.Validate(); err != nil {
		t.Fatal(err)
	}
	repair.RepairID = "repair with spaces"
	if err := repair.Validate(); err == nil {
		t.Fatal("Validate() accepted a non-canonical repair operation identity")
	}
}
