// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
// SPDX-License-Identifier: Apache-2.0

package spec

import (
	"encoding/json"
	"testing"

	"github.com/go-openapi/swag/conv"
	"github.com/go-openapi/testify/v2/assert"
	"github.com/go-openapi/testify/v2/require"
)

var schema = Schema{ //nolint:gochecknoglobals // test fixture
	VendorExtensible: VendorExtensible{Extensions: map[string]any{"x-framework": "go-swagger"}},
	SchemaProps: SchemaProps{
		Ref:              MustCreateRef("Cat"),
		Type:             []string{"string"},
		Format:           "date",
		Description:      "the description of this schema",
		Title:            "the title",
		Default:          "blah",
		Maximum:          float64Ptr(100),
		ExclusiveMaximum: true,
		ExclusiveMinimum: true,
		Minimum:          float64Ptr(5),
		MaxLength:        int64Ptr(100),
		MinLength:        int64Ptr(5),
		Pattern:          "\\w{1,5}\\w+",
		MaxItems:         int64Ptr(100),
		MinItems:         int64Ptr(5),
		UniqueItems:      true,
		MultipleOf:       float64Ptr(5),
		Enum:             []any{"hello", "world"},
		MaxProperties:    int64Ptr(5),
		MinProperties:    int64Ptr(1),
		Required:         []string{"id", "name"},
		Items:            &SchemaOrArray{Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}},
		AllOf:            []Schema{{SchemaProps: SchemaProps{Type: []string{"string"}}}},
		Properties: map[string]Schema{
			"id":   {SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}},
			"name": {SchemaProps: SchemaProps{Type: []string{"string"}}},
		},
		AdditionalProperties: &SchemaOrBool{Allows: true, Schema: &Schema{SchemaProps: SchemaProps{
			Type:   []string{"integer"},
			Format: "int32",
		}}},
	},
	SwaggerSchemaProps: SwaggerSchemaProps{
		Discriminator: "not this",
		ReadOnly:      true,
		XML:           &XMLObject{Name: "sch", Namespace: "io", Prefix: "sw", Attribute: true, Wrapped: true},
		ExternalDocs: &ExternalDocumentation{
			Description: "the documentation etc",
			URL:         "http://readthedocs.org/swagger",
		},
		Example: []any{
			map[string]any{
				"id":   1,
				"name": "a book",
			},
			map[string]any{
				"id":   2,
				"name": "the thing",
			},
		},
	},
}

//nolint:gochecknoglobals // test fixture
var schemaJSON = `{
	"x-framework": "go-swagger",
  "$ref": "Cat",
  "description": "the description of this schema",
  "maximum": 100,
  "minimum": 5,
  "exclusiveMaximum": true,
  "exclusiveMinimum": true,
  "maxLength": 100,
  "minLength": 5,
  "pattern": "\\w{1,5}\\w+",
  "maxItems": 100,
  "minItems": 5,
  "uniqueItems": true,
  "multipleOf": 5,
  "enum": ["hello", "world"],
  "type": "string",
  "format": "date",
  "title": "the title",
  "default": "blah",
  "maxProperties": 5,
  "minProperties": 1,
  "required": ["id", "name"],
  "items": {
    "type": "string"
  },
  "allOf": [
    {
      "type": "string"
    }
  ],
  "properties": {
    "id": {
      "type": "integer",
      "format": "int64"
    },
    "name": {
      "type": "string"
    }
  },
  "discriminator": "not this",
  "readOnly": true,
  "xml": {
    "name": "sch",
    "namespace": "io",
    "prefix": "sw",
    "wrapped": true,
    "attribute": true
  },
  "externalDocs": {
    "description": "the documentation etc",
    "url": "http://readthedocs.org/swagger"
  },
  "example": [
    {
      "id": 1,
      "name": "a book"
    },
    {
      "id": 2,
      "name": "the thing"
    }
  ],
  "additionalProperties": {
    "type": "integer",
    "format": "int32"
  }
}
`

func TestSchema(t *testing.T) {
	assert.JSONMarshalAsT(t, schemaJSON, schema)

	actual2 := Schema{}
	require.NoError(t, json.Unmarshal([]byte(schemaJSON), &actual2))

	assert.Equal(t, schema.Ref, actual2.Ref)
	assert.EqualT(t, schema.Description, actual2.Description)
	assert.Equal(t, schema.Maximum, actual2.Maximum)
	assert.Equal(t, schema.Minimum, actual2.Minimum)
	assert.EqualT(t, schema.ExclusiveMinimum, actual2.ExclusiveMinimum)
	assert.EqualT(t, schema.ExclusiveMaximum, actual2.ExclusiveMaximum)
	assert.Equal(t, schema.MaxLength, actual2.MaxLength)
	assert.Equal(t, schema.MinLength, actual2.MinLength)
	assert.EqualT(t, schema.Pattern, actual2.Pattern)
	assert.Equal(t, schema.MaxItems, actual2.MaxItems)
	assert.Equal(t, schema.MinItems, actual2.MinItems)
	assert.TrueT(t, actual2.UniqueItems)
	assert.Equal(t, schema.MultipleOf, actual2.MultipleOf)
	assert.Equal(t, schema.Enum, actual2.Enum)
	assert.Equal(t, schema.Type, actual2.Type)
	assert.EqualT(t, schema.Format, actual2.Format)
	assert.EqualT(t, schema.Title, actual2.Title)
	assert.Equal(t, schema.MaxProperties, actual2.MaxProperties)
	assert.Equal(t, schema.MinProperties, actual2.MinProperties)
	assert.Equal(t, schema.Required, actual2.Required)
	assert.Equal(t, schema.Items, actual2.Items)
	assert.Equal(t, schema.AllOf, actual2.AllOf)
	assert.Equal(t, schema.Properties, actual2.Properties)
	assert.EqualT(t, schema.Discriminator, actual2.Discriminator)
	assert.EqualT(t, schema.ReadOnly, actual2.ReadOnly)
	assert.Equal(t, schema.XML, actual2.XML)
	assert.Equal(t, schema.ExternalDocs, actual2.ExternalDocs)
	assert.Equal(t, schema.AdditionalProperties, actual2.AdditionalProperties)
	assert.Equal(t, schema.Extensions, actual2.Extensions)

	examples, ok := actual2.Example.([]any)
	require.TrueT(t, ok, "expected []any for actual2.Example")
	expEx, ok := schema.Example.([]any)
	require.TrueT(t, ok, "expected []any for schema.Example")
	ex1, ok := examples[0].(map[string]any)
	require.TrueT(t, ok, "expected map[string]any for examples[0]")
	ex2, ok := examples[1].(map[string]any)
	require.TrueT(t, ok, "expected map[string]any for examples[1]")
	exp1, ok := expEx[0].(map[string]any)
	require.TrueT(t, ok, "expected map[string]any for expEx[0]")
	exp2, ok := expEx[1].(map[string]any)
	require.TrueT(t, ok, "expected map[string]any for expEx[1]")

	assert.EqualValues(t, exp1["id"], ex1["id"])
	assert.Equal(t, exp1["name"], ex1["name"])
	assert.EqualValues(t, exp2["id"], ex2["id"])
	assert.Equal(t, exp2["name"], ex2["name"])
}

func BenchmarkSchemaUnmarshal(b *testing.B) {
	for b.Loop() {
		sch := &Schema{}
		_ = sch.UnmarshalJSON([]byte(schemaJSON))
	}
}

func TestSchemaWithValidation(t *testing.T) {
	s := new(Schema).WithValidations(SchemaValidations{CommonValidations: CommonValidations{MaxLength: conv.Pointer(int64(15))}})
	assert.Equal(t, conv.Pointer(int64(15)), s.MaxLength)

	val := mkVal()
	s = new(Schema).WithValidations(val)

	assert.Equal(t, val, s.Validations())
}
