package shape

import (
	"context"
	"reflect"
	"strings"
	"testing"

	"gitea.maximumdirect.net/eric/notarius/internal/core/source"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
	"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
)

func TestValidatorRejectsMalformedItemsWithoutMutation(t *testing.T) {
	value := dnd.ItemRegistry{Items: []dnd.Item{{Name: "", SourceRefs: []source.SourceRef{}}}}
	before := value
	result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemRegistry]{Value: value})
	if err != nil || result.Approved || result.ReasonCode != ReasonCode || !strings.Contains(result.Message, "id must not be empty") || !strings.Contains(result.Message, "source_refs must not be empty") || !reflect.DeepEqual(value, before) {
		t.Fatalf("Validate() = %#v, %v; want non-mutating shape rejection", result, err)
	}
	result, err = New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemRegistry]{Value: dnd.ItemRegistry{}})
	if err != nil || result.Approved || !strings.Contains(result.Message, "items must be present") {
		t.Fatalf("missing items = %#v, %v; want rejection", result, err)
	}
}

func TestValidatorApprovesAndRegisters(t *testing.T) {
	value := dnd.ItemRegistry{Items: []dnd.Item{{ID: "item", Name: "Rope", SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}}}
	result, err := New(Options{}).Validate(context.Background(), contracts.TypedValidationRequest[dnd.ItemRegistry]{Value: value})
	if err != nil || !result.Approved {
		t.Fatalf("Validate() = %#v, %v; want approval", result, err)
	}
	registry := pipeline.NewValidatorRegistry()
	if err := Register(registry); err != nil {
		t.Fatalf("Register() error = %v", err)
	}
	if got, ok := registry.Spec(Key); !ok || got != Spec() || got.ExecutionClass != contracts.ExecutionClassDeterministic {
		t.Fatalf("registered spec = %#v, ok = %t", got, ok)
	}
	if _, err := DecodeOptions(map[string]any{"unexpected": true}); err == nil {
		t.Fatal("DecodeOptions() accepted unknown options")
	}
}
