package registry

import (
	"context"
	"encoding/json"
	"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"
	locationcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/locationregistry"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/locations/identity"
	locationregistry "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/locations/registry"
)

func TestValidatorDistinguishesSameNameLocationsByID(t *testing.T) {
	references, first, second := registryReferences(t)
	value := dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{
		occurrence(first.ID, first.Name), occurrence(second.ID, second.Name),
	}}
	validator := newValidator(t, references)
	before := cloneList(value)
	result, err := validator.Validate(context.Background(), request(references, value))
	if err != nil || !result.Approved || !reflect.DeepEqual(value, before) {
		t.Fatalf("matching IDs = %#v, %v", result, err)
	}
	value.Occurrences[0].Name = "Sun Gate"
	result, err = validator.Validate(context.Background(), request(references, value))
	if err != nil || result.Approved || result.ReasonCode != ReasonCode || !strings.Contains(result.Message, "does not match registry location") {
		t.Fatalf("mismatched name = %#v, %v", result, err)
	}
	value.Occurrences[0].LocationID = "location:unknown"
	result, err = validator.Validate(context.Background(), request(references, value))
	if err != nil || result.Approved || !strings.Contains(result.Message, "is not in the location registry") {
		t.Fatalf("unknown ID = %#v, %v", result, err)
	}
}

func TestValidatorRequiresAndSafelyPreparesRegistry(t *testing.T) {
	value := dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{occurrence("location:one", "Moon Gate")}}
	result, err := newValidator(t).Validate(context.Background(), request(contracts.ReferenceSet{}, value))
	if err != nil || result.Approved || !strings.Contains(result.Message, "required") {
		t.Fatalf("missing registry = %#v, %v", result, err)
	}
	malformed := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{locationregistry.ReferenceSlot: {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte(`{"secret":"private"}`)}}}}}
	if _, err := New(Options{}, malformed); err == nil || strings.Contains(err.Error(), "private") {
		t.Fatalf("New() error = %v", err)
	}
	references, _, _ := registryReferences(t)
	metadata, err := json.Marshal(newValidator(t, references).ManifestMetadata())
	if err != nil || strings.Contains(string(metadata), "Moon Gate") {
		t.Fatalf("metadata = %s, %v", metadata, err)
	}
	if got := newValidator(t, references).CheckpointFingerprints(); len(got) != 2 || got[0].Value != policy || !strings.HasPrefix(got[1].Value, "sha256:") {
		t.Fatalf("fingerprints = %#v", got)
	}
}

func TestValidatorRegistersAndDefersShape(t *testing.T) {
	references, _, _ := registryReferences(t)
	result, err := newValidator(t, references).Validate(context.Background(), request(references, dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{{Name: "Missing"}}}))
	if err != nil || !result.Approved {
		t.Fatalf("shape deferral = %#v, %v", result, err)
	}
	registry := pipeline.NewValidatorRegistry()
	if err := Register(registry); err != nil {
		t.Fatal(err)
	}
	if got, ok := registry.Spec(Key); !ok || got != Spec() || got.ExecutionClass != contracts.ExecutionClassDeterministic {
		t.Fatalf("registered spec = %#v, ok = %t", got, ok)
	}
}

func newValidator(t *testing.T, references ...contracts.ReferenceSet) *Validator {
	t.Helper()
	validator, err := New(Options{}, references...)
	if err != nil {
		t.Fatal(err)
	}
	return validator
}
func request(references contracts.ReferenceSet, value dnd.LocationOccurrenceList) contracts.TypedValidationRequest[dnd.LocationOccurrenceList] {
	return contracts.TypedValidationRequest[dnd.LocationOccurrenceList]{References: references, Value: value}
}
func occurrence(id, name string) dnd.LocationOccurrence {
	return dnd.LocationOccurrence{LocationID: id, Name: name, Kind: dnd.LocationOccurrenceKindVisited, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}
}
func cloneList(value dnd.LocationOccurrenceList) dnd.LocationOccurrenceList {
	cloned := dnd.LocationOccurrenceList{Occurrences: append([]dnd.LocationOccurrence(nil), value.Occurrences...)}
	for index := range cloned.Occurrences {
		cloned.Occurrences[index].SourceRefs = append([]source.SourceRef(nil), value.Occurrences[index].SourceRefs...)
	}
	return cloned
}
func registryReferences(t *testing.T) (contracts.ReferenceSet, dnd.Location, dnd.Location) {
	t.Helper()
	firstRefs := []source.SourceRef{{SourceID: "source", StartUnitID: 1, EndUnitID: 1}}
	secondRefs := []source.SourceRef{{SourceID: "source", StartUnitID: 2, EndUnitID: 2}}
	first := dnd.Location{ID: identity.DeriveID("Moon Gate", firstRefs), Name: "Moon Gate", SourceRefs: firstRefs}
	second := dnd.Location{ID: identity.DeriveID("Moon Gate", secondRefs), Name: "Moon Gate", SourceRefs: secondRefs}
	thirdRefs := []source.SourceRef{{SourceID: "source", StartUnitID: 3, EndUnitID: 3}}
	third := dnd.Location{ID: identity.DeriveID("Sun Gate", thirdRefs), Name: "Sun Gate", SourceRefs: thirdRefs}
	content, err := locationcodec.New().Encode(dnd.LocationRegistry{Locations: []dnd.Location{first, second, third}})
	if err != nil {
		t.Fatal(err)
	}
	return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{locationregistry.ReferenceSlot: {Slot: contracts.ReferenceSlot{Name: locationregistry.ReferenceSlot}, Items: []contracts.ReferenceItem{{SlotName: locationregistry.ReferenceSlot, MediaType: locationcodec.MediaType, Content: content, Origin: contracts.ReferenceOrigin{Type: "generated"}}}}}}, first, second
}
