package locationoccurrences

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

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

func TestResponseSchemaRestrictsPrivateOccurrenceStructureAndKinds(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": "The Mill", "registry_refs": []any{map[string]any{"start_unit_id": 1, "end_unit_id": 2}}, "kind": "visited",
		"source_refs": []any{map[string]any{"start_unit_id": 1, "end_unit_id": 2}},
	}}}
	if err := validateSchema(t, valid, schema.JSONSchema); err != nil {
		t.Fatalf("valid response rejected: %v", err)
	}
	for _, mutate := range []func(map[string]any){
		func(value map[string]any) { delete(value, "registry_refs") },
		func(value map[string]any) { value["kind"] = "other" },
		func(value map[string]any) { value["unexpected"] = true },
		func(value map[string]any) { value["registry_refs"].([]any)[0].(map[string]any)["start_unit_id"] = 0 },
		func(value map[string]any) {
			value["source_refs"].([]any)[0].(map[string]any)["source_id"] = "assigned later"
		},
	} {
		candidate := cloneCandidate(t, valid)
		mutate(candidate["occurrences"].([]any)[0].(map[string]any))
		if err := validateSchema(t, candidate, schema.JSONSchema); err == nil {
			t.Fatal("schema accepted structurally invalid response")
		}
	}
}

func TestResponseSchemaIsDefensiveAndContentSafe(t *testing.T) {
	first, err := loadResponseSchema()
	if err != nil {
		t.Fatal(err)
	}
	first.JSONSchema[0] = '['
	second, err := loadResponseSchema()
	if err != nil || !json.Valid(second.JSONSchema) || bytes.Equal(first.JSONSchema, second.JSONSchema) {
		t.Fatalf("schema = %s, %v", second.JSONSchema, err)
	}
	if diagnostics := second.DiagnosticsMap(); diagnostics["key"] != ResponseSchemaKey || diagnostics["id"] != ResponseSchemaID {
		t.Fatalf("diagnostics = %#v", diagnostics)
	} else if _, ok := diagnostics["json_schema"]; ok {
		t.Fatalf("diagnostics leaked schema content: %#v", diagnostics)
	}
}

func cloneCandidate(t *testing.T, value map[string]any) map[string]any {
	t.Helper()
	content, err := json.Marshal(value)
	if err != nil {
		t.Fatal(err)
	}
	var clone map[string]any
	if err := json.Unmarshal(content, &clone); err != nil {
		t.Fatal(err)
	}
	return clone
}

func validateSchema(t *testing.T, value map[string]any, schemaContent []byte) error {
	t.Helper()
	content, err := json.Marshal(value)
	if err != nil {
		return err
	}
	instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(content))
	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
	}
	schema, err := compiler.Compile("schema.json")
	if err != nil {
		return err
	}
	return schema.Validate(instance)
}
