package spec

import (
	"testing"
	"testing/fstest"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestSchema_Draft202012Enforced(t *testing.T) {
	t.Parallel()

	cases := []struct {
		name    string
		schema  map[string]any
		wantSub string
	}{
		{
			name:    "missing dialect uri rejected",
			schema:  map[string]any{"type": "object"},
			wantSub: "$schema",
		},
		{
			name:    "wrong dialect rejected",
			schema:  map[string]any{"$schema": "http://json-schema.org/draft-07/schema#", "type": "object"},
			wantSub: "2020-12",
		},
		{
			name:    "pre-2020 keyword rejected",
			schema:  map[string]any{"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "definitions": map[string]any{}},
			wantSub: "pre-2020",
		},
	}
	for _, tc := range cases {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			p := validStructPackage()
			p.Actions[0].Catalog.InputSchema = tc.schema
			_, err := LoadDefinition(pkgToFS(t, p), "pkg")
			require.Error(t, err)
			assert.Contains(t, err.Error(), tc.wantSub)
		})
	}
}

func TestSchema_CompilesValidDraft2020WithRefs(t *testing.T) {
	m := fstest.MapFS{
		"pkg/meta.yaml": {Data: []byte(`schema_version: 1
domain: demo
version: 1
name: Demo
endpoint:
  base_url: https://api.demo.example.com
actions:
  - name: do-thing
    file: actions/do-thing.yaml
`)},
		"pkg/actions/do-thing.yaml": {Data: []byte(`name: do-thing
catalog:
  summary: x
  safety: {class: read}
  input_schema:
    $schema: https://json-schema.org/draft/2020-12/schema
    type: object
    additionalProperties: false
    required: [n]
    properties:
      n:
        $ref: "#/$defs/pos"
    $defs:
      pos:
        type: integer
        minimum: 0
binding:
  method: GET
  path: /things
  response: {mode: passthrough, success_statuses: [200], content_types: [application/json]}
`)},
	}
	pkg, err := LoadDefinition(m, "pkg")
	require.NoError(t, err)
	assert.Equal(t, "do-thing", pkg.Actions[0].Name)
}
