package pipeline

import "testing"

func TestValidatorChainRegistryRegistersAndLooksUpChains(t *testing.T) {
	registry := NewValidatorChainRegistry()
	err := registry.Register(ValidatorChainMapping{
		Stage:      StageExtract,
		Module:     " extractor ",
		Validators: []ModuleBinding{{Module: " first "}, {Module: "second"}},
	})
	if err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	got := registry.Validators(StageExtract, " extractor ")
	if len(got) != 2 || got[0].Module != "first" || got[1].Module != "second" {
		t.Fatalf("Validators() = %#v, want trimmed chain", got)
	}
}

func TestValidatorChainRegistryRejectsDuplicateMappings(t *testing.T) {
	registry := NewValidatorChainRegistry()
	mapping := ValidatorChainMapping{Stage: StageMerge, Module: "merge", Validators: []ModuleBinding{Binding("validator")}}
	if err := registry.Register(mapping); err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	if err := registry.Register(mapping); err == nil {
		t.Fatal("Register() error = nil, want duplicate mapping error")
	}
}

func TestValidatorChainRegistryRejectsUnsupportedStage(t *testing.T) {
	registry := NewValidatorChainRegistry()
	err := registry.Register(ValidatorChainMapping{Stage: StageInput, Module: "input"})
	if err == nil {
		t.Fatal("Register() error = nil, want unsupported stage error")
	}
}

func TestValidatorChainRegistryAllowsAbsentAndEmptyChains(t *testing.T) {
	registry := NewValidatorChainRegistry()
	if got := registry.Validators(StageNormalize, "normalize"); got != nil {
		t.Fatalf("absent chain = %#v, want nil", got)
	}
	if err := registry.Register(ValidatorChainMapping{Stage: StageNormalize, Module: "normalize"}); err != nil {
		t.Fatalf("Register(empty) error = %v, want nil", err)
	}
	if got := registry.Validators(StageNormalize, "normalize"); got != nil {
		t.Fatalf("empty chain = %#v, want nil", got)
	}
}

func TestValidatorChainRegistryReturnsDefensiveCopies(t *testing.T) {
	registry := NewValidatorChainRegistry()
	err := registry.Register(ValidatorChainMapping{
		Stage:      StageChunk,
		Module:     "chunk",
		Validators: []ModuleBinding{{Module: "validator", Options: map[string]any{"level": "strict"}}},
	})
	if err != nil {
		t.Fatalf("Register() error = %v, want nil", err)
	}

	got := registry.Validators(StageChunk, "chunk")
	got[0].Module = "changed"
	got[0].Options["level"] = "changed"

	again := registry.Validators(StageChunk, "chunk")
	if again[0].Module != "validator" || again[0].Options["level"] != "strict" {
		t.Fatalf("Validators() after caller mutation = %#v, want original chain", again)
	}
}
