package itemoccurrences

import (
	"bytes"
	"encoding/json"
	"strings"
	"testing"

	"github.com/santhosh-tekuri/jsonschema/v6"
)

func TestResponseSchemaIsStrictlyStructuralAndPrivate(t *testing.T) {
	schema, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	if schema.Key != ResponseSchemaKey || schema.ID != ResponseSchemaID || schema.Name != ResponseSchemaName || schema.Version != SchemaVersion || !strings.HasPrefix(schema.SHA256, "sha256:") || !json.Valid(schema.JSONSchema) {
		t.Fatalf("schema = %#v", schema)
	}
	valid := map[string]any{"occurrences": []any{
		map[string]any{
			"name": "", "kind": "transferred", "quantity": 0, "from": "party", "to": "Party",
			"source_refs": []any{map[string]any{"start_unit_id": 0, "end_unit_id": -1}},
		},
		map[string]any{
			"name": "Hidden Cache", "kind": "discovered", "quantity": nil, "from": nil, "to": nil,
			"source_refs": []any{map[string]any{"start_unit_id": 1, "end_unit_id": 1}},
		},
	}}
	content, err := json.Marshal(valid)
	if err != nil {
		t.Fatal(err)
	}
	if err := validateJSONSchema(content, schema.JSONSchema); err != nil {
		t.Fatalf("private schema rejected validator-owned values: %v", err)
	}
	for _, test := range []struct {
		name  string
		value map[string]any
	}{
		{"missing occurrences", map[string]any{}},
		{"missing occurrence name", map[string]any{"occurrences": []any{withoutField(responseOccurrence(), "name")}}},
		{"missing nullable field", map[string]any{"occurrences": []any{withoutField(responseOccurrence(), "quantity")}}},
		{"unsupported kind", map[string]any{"occurrences": []any{withField(responseOccurrence(), "kind", "unsupported")}}},
		{"opaque item identifier", map[string]any{"occurrences": []any{withField(responseOccurrence(), "item_id", "item:sha256:opaque")}}},
		{"unknown occurrence field", map[string]any{"occurrences": []any{withField(responseOccurrence(), "extra", true)}}},
		{"segment-named range", map[string]any{"occurrences": []any{withField(responseOccurrence(), "source_refs", []any{map[string]any{"start_segment": 1, "end_segment": 1}})}}},
		{"opaque source identifier", map[string]any{"occurrences": []any{withField(responseOccurrence(), "source_refs", []any{map[string]any{"start_unit_id": 1, "end_unit_id": 1, "source_id": "session-alpha"}})}}},
		{"unknown reference field", map[string]any{"occurrences": []any{withField(responseOccurrence(), "source_refs", []any{map[string]any{"start_unit_id": 1, "end_unit_id": 1, "extra": true}})}}},
		{"noninteger range", map[string]any{"occurrences": []any{withField(responseOccurrence(), "source_refs", []any{map[string]any{"start_unit_id": 1.5, "end_unit_id": 1}})}}},
	} {
		t.Run(test.name, func(t *testing.T) {
			content, err := json.Marshal(test.value)
			if err != nil {
				t.Fatal(err)
			}
			if err := validateJSONSchema(content, schema.JSONSchema); err == nil {
				t.Fatal("private schema accepted invalid structure")
			}
		})
	}
	first := schema.JSONSchema
	first[0] = '['
	second, err := loadResponseSchema()
	if err != nil || !json.Valid(second.JSONSchema) || bytes.Equal(first, second.JSONSchema) {
		t.Fatalf("defensive schema copy = %s, %v", second.JSONSchema, err)
	}
	if _, ok := second.DiagnosticsMap()["json_schema"]; ok {
		t.Fatalf("schema diagnostics leaked content: %#v", second.DiagnosticsMap())
	}
}

func responseOccurrence() map[string]any {
	return map[string]any{
		"name": "Ring", "kind": "acquired", "quantity": nil, "from": nil, "to": "party", "source_refs": []any{},
	}
}

func withoutField(value map[string]any, name string) map[string]any {
	delete(value, name)
	return value
}

func withField(value map[string]any, name string, fieldValue any) map[string]any {
	value[name] = fieldValue
	return value
}

func validateJSONSchema(instanceContent, schemaContent []byte) error {
	instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(instanceContent))
	if err != nil {
		return err
	}
	document, err := jsonschema.UnmarshalJSON(bytes.NewReader(schemaContent))
	if err != nil {
		return err
	}
	compiler := jsonschema.NewCompiler()
	if err := compiler.AddResource("schema.json", document); err != nil {
		return err
	}
	compiled, err := compiler.Compile("schema.json")
	if err != nil {
		return err
	}
	return compiled.Validate(instance)
}
