package itemregistry

import (
	"bytes"
	"encoding/json"
	"os"
	"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/modules/dnd"
	"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/items/identity"
)

func validRegistry() dnd.ItemRegistry {
	return dnd.ItemRegistry{Items: []dnd.Item{{
		ID:         identity.DeriveID("Silver Key"),
		Name:       "Silver Key",
		SourceRefs: []source.SourceRef{{SourceID: "session-alpha", StartUnitID: 1, EndUnitID: 2}},
	}}}
}

func TestCodecMatchesMaintainedDurableFixture(t *testing.T) {
	raw, err := os.ReadFile("testdata/dnd_item_registry.v1.json")
	if err != nil {
		t.Fatalf("read durable fixture: %v", err)
	}
	codec := New()
	value, err := codec.Decode(raw)
	if err != nil {
		t.Fatalf("Decode() error = %v", err)
	}
	if want := validRegistry(); !reflect.DeepEqual(value, want) {
		t.Fatalf("Decode() = %#v, want %#v", value, want)
	}
	encoded, err := codec.Encode(value)
	if err != nil {
		t.Fatalf("Encode() error = %v", err)
	}
	var compact bytes.Buffer
	if err := json.Compact(&compact, raw); err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(encoded, compact.Bytes()) {
		t.Fatalf("Encode() = %s, want %s", encoded, compact.Bytes())
	}
}

func TestCodecOwnsDurableSchemaAndExactType(t *testing.T) {
	codec := New()
	schema := codec.Schema()
	if codec.Kind() != dnd.ItemRegistryKind || codec.MediaType() != MediaType || schema.ID != SchemaID || schema.Name != SchemaName || schema.Version != SchemaVersion || !json.Valid(schema.JSONSchema) {
		t.Fatalf("codec contract = %#v / %#v", codec, schema)
	}
}

func TestCodecCandidateEncodingMetadataAndStrictDecode(t *testing.T) {
	codec := New()
	candidate := dnd.ItemRegistry{Items: []dnd.Item{{Name: "Silver Key"}}}
	content, err := codec.EncodeCandidate(candidate)
	if err != nil || string(content) != `{"items":[{"id":"","name":"Silver Key","source_refs":null}]}` {
		t.Fatalf("EncodeCandidate() = %s, %v", content, err)
	}
	if decoded, err := codec.DecodeCandidate(content); err != nil || !reflect.DeepEqual(decoded, candidate) {
		t.Fatalf("DecodeCandidate() = %#v, %v; want %#v", decoded, err, candidate)
	}
	if _, err := codec.Encode(candidate); err == nil || !strings.Contains(err.Error(), "item ID pattern") {
		t.Fatalf("Encode() error = %v, want durable validation", err)
	}
	metadata := codec.Metadata(validRegistry())
	if metadata["item_count"] != 1 {
		t.Fatalf("Metadata() = %#v", metadata)
	}
	for _, content := range []string{
		`{"items":[],"unexpected":true}`,
		`{"items":[{"id":"` + identity.DeriveID("Silver Key") + `","name":"Silver Key","source_refs":[{"source_id":"s","start_unit_id":1,"end_unit_id":1,"unexpected":true}]}]}`,
		`{"items":[]} {}`,
	} {
		if _, err := codec.Decode([]byte(content)); err == nil {
			t.Fatalf("Decode(%s) error = nil", content)
		}
	}
}

func TestCodecCandidateDecodeOwnsValues(t *testing.T) {
	codec := New()
	input := validRegistry()
	content, err := codec.EncodeCandidate(input)
	if err != nil {
		t.Fatal(err)
	}
	first, err := codec.DecodeCandidate(content)
	if err != nil {
		t.Fatal(err)
	}
	second, err := codec.DecodeCandidate(content)
	if err != nil {
		t.Fatal(err)
	}
	nameOffset := bytes.Index(content, []byte("Silver Key"))
	if nameOffset < 0 {
		t.Fatal("candidate JSON does not contain item name")
	}
	content[nameOffset] = 'X'
	if first.Items[0].Name != "Silver Key" {
		t.Fatal("DecodeCandidate() retained input bytes")
	}
	first.Items[0].Name = "changed"
	first.Items[0].SourceRefs[0].SourceID = "changed"
	if input.Items[0].Name != "Silver Key" || input.Items[0].SourceRefs[0].SourceID != "session-alpha" {
		t.Fatal("DecodeCandidate() retained input values")
	}
	if second.Items[0].Name != "Silver Key" || second.Items[0].SourceRefs[0].SourceID != "session-alpha" {
		t.Fatal("DecodeCandidate() returned aliased values")
	}
}

func TestCodecRejectsInvalidDurableRangesWhileCandidatesPreserveThem(t *testing.T) {
	codec := New()
	for _, test := range []struct {
		name   string
		mutate func(*dnd.ItemRegistry)
		want   string
	}{
		{name: "nonpositive start", mutate: func(value *dnd.ItemRegistry) { value.Items[0].SourceRefs[0].StartUnitID = 0 }, want: "start_unit_id"},
		{name: "nonpositive end", mutate: func(value *dnd.ItemRegistry) { value.Items[0].SourceRefs[0].EndUnitID = 0 }, want: "end_unit_id"},
		{name: "reversed", mutate: func(value *dnd.ItemRegistry) {
			value.Items[0].SourceRefs[0].StartUnitID = 2
			value.Items[0].SourceRefs[0].EndUnitID = 1
		}, want: "must not exceed"},
	} {
		t.Run(test.name, func(t *testing.T) {
			candidate := validRegistry()
			test.mutate(&candidate)
			content, err := codec.EncodeCandidate(candidate)
			if err != nil {
				t.Fatalf("EncodeCandidate() error = %v", err)
			}
			decoded, err := codec.DecodeCandidate(content)
			if err != nil || !reflect.DeepEqual(decoded, candidate) {
				t.Fatalf("DecodeCandidate() = %#v, %v; want %#v", decoded, err, candidate)
			}
			if _, err := codec.Encode(candidate); err == nil || !strings.Contains(err.Error(), test.want) {
				t.Fatalf("Encode() error = %v, want %q", err, test.want)
			}
			if _, err := codec.Decode(content); err == nil || !strings.Contains(err.Error(), test.want) {
				t.Fatalf("Decode() error = %v, want %q", err, test.want)
			}
		})
	}
}

func TestCodecSchemaAndMetadataAreDefensive(t *testing.T) {
	codec := New()
	first := codec.Schema()
	first.JSONSchema[0] = '['
	if next := codec.Schema(); !json.Valid(next.JSONSchema) || next.JSONSchema[0] == '[' {
		t.Fatal("Schema() returned shared bytes")
	}
	metadata := codec.Metadata(validRegistry())
	metadata["other"] = true
	if next := codec.Metadata(validRegistry()); len(next) != 1 || next["item_count"] != 1 {
		t.Fatalf("Metadata() = %#v", next)
	}
}

var _ contracts.ArtifactCodec[dnd.ItemRegistry] = (*Codec)(nil)
