package shape

import (
	"context"
	"reflect"
	"strings"
	"testing"
	"unicode/utf8"

	"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 TestValidatorRejectsMissingRequiredFieldsWithoutMutation(t *testing.T) {
	value := dnd.LocationRegistry{Locations: []dnd.Location{{Name: strings.Repeat("火", 220), SourceRefs: []source.SourceRef{}}}}
	before := value
	result, err := New(Options{}).Validate(context.Background(), requestWithValue(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") {
		t.Fatalf("Validate() = %#v, %v; want shape rejection", result, err)
	}
	if len(result.Message) > 4096 || !utf8.ValidString(result.Message) || !reflect.DeepEqual(value, before) {
		t.Fatalf("Validate() produced unsafe diagnostics or mutated value: %#v", value)
	}
	result, err = New(Options{}).Validate(context.Background(), requestWithValue(dnd.LocationRegistry{}))
	if err != nil || result.Approved || !strings.Contains(result.Message, "locations must be present") {
		t.Fatalf("missing locations = %#v, %v; want rejection", result, err)
	}
}

func TestValidatorApprovesAndRegisters(t *testing.T) {
	result, err := New(Options{}).Validate(context.Background(), requestWithValue(validLocationRegistry()))
	if err != nil || !result.Approved {
		t.Fatalf("Validate() = %#v, %v; want approval", result, err)
	}
	if got := New(Options{}).CheckpointFingerprints(); len(got) != 1 || got[0].Name != "policy" || got[0].Value != policy {
		t.Fatalf("CheckpointFingerprints() = %#v", got)
	}
	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 an unknown option")
	}
}

func requestWithValue(value dnd.LocationRegistry) contracts.TypedValidationRequest[dnd.LocationRegistry] {
	return contracts.TypedValidationRequest[dnd.LocationRegistry]{Value: value}
}

func validLocationRegistry() dnd.LocationRegistry {
	return dnd.LocationRegistry{Locations: []dnd.Location{{ID: "candidate", Name: "Moon Gate", SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}}}
}
