// Copyright 2022 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT

package base

import (
	"context"
	"testing"

	"github.com/pb33f/libopenapi/datamodel/low"
	"github.com/pb33f/libopenapi/index"
	"github.com/pb33f/libopenapi/orderedmap"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.yaml.in/yaml/v4"
)

func TestExample_Build_Success_NoValue(t *testing.T) {
	yml := `summary: hot
description: cakes
x-cake: hot`

	var idxNode yaml.Node
	mErr := yaml.Unmarshal([]byte(yml), &idxNode)
	assert.NoError(t, mErr)
	idx := index.NewSpecIndexWithConfig(&idxNode, index.CreateClosedAPIIndexConfig())

	var n Example
	err := low.BuildModel(idxNode.Content[0], &n)
	assert.NoError(t, err)

	err = n.Build(context.Background(), nil, idxNode.Content[0], idx)
	assert.NoError(t, err)
	assert.Equal(t, "hot", n.Summary.Value)
	assert.Equal(t, "cakes", n.Description.Value)
	assert.Nil(t, n.Value.Value)

	var xCake string
	_ = n.FindExtension("x-cake").Value.Decode(&xCake)
	assert.Equal(t, "hot", xCake)
	assert.NotNil(t, n.GetRootNode())
	assert.Nil(t, n.GetKeyNode())
	assert.NotNil(t, n.GetContext())
	assert.NotNil(t, n.GetIndex())
}

func TestExample_Build_Success_Simple(t *testing.T) {
	yml := `summary: hot
description: cakes
value: a string example
x-cake: hot`

	var idxNode yaml.Node
	mErr := yaml.Unmarshal([]byte(yml), &idxNode)
	assert.NoError(t, mErr)
	idx := index.NewSpecIndexWithConfig(&idxNode, index.CreateClosedAPIIndexConfig())

	var n Example
	err := low.BuildModel(idxNode.Content[0], &n)
	assert.NoError(t, err)

	err = n.Build(context.Background(), nil, idxNode.Content[0], idx)
	assert.NoError(t, err)
	assert.Equal(t, "hot", n.Summary.Value)
	assert.Equal(t, "cakes", n.Description.Value)

	var example string
	err = n.Value.Value.Decode(&example)
	require.NoError(t, err)
	assert.Equal(t, "a string example", example)

	var xCake string
	_ = n.FindExtension("x-cake").Value.Decode(&xCake)
	assert.Equal(t, "hot", xCake)
}

func TestExample_Build_Success_Object(t *testing.T) {
	yml := `summary: hot
description: cakes
value:
  pizza: oven
  yummy: pizza`

	var idxNode yaml.Node
	mErr := yaml.Unmarshal([]byte(yml), &idxNode)
	assert.NoError(t, mErr)
	idx := index.NewSpecIndexWithConfig(&idxNode, index.CreateClosedAPIIndexConfig())

	var n Example
	err := low.BuildModel(idxNode.Content[0], &n)
	assert.NoError(t, err)

	err = n.Build(context.Background(), nil, idxNode.Content[0], idx)
	assert.NoError(t, err)
	assert.Equal(t, "hot", n.Summary.Value)
	assert.Equal(t, "cakes", n.Description.Value)

	var m map[string]interface{}
	err = n.Value.Value.Decode(&m)
	require.NoError(t, err)

	assert.Equal(t, "oven", m["pizza"])
	assert.Equal(t, "pizza", m["yummy"])
}

func TestExample_Build_Success_Array(t *testing.T) {
	yml := `summary: hot
description: cakes
value:
  - wow
  - such array`

	var idxNode yaml.Node
	mErr := yaml.Unmarshal([]byte(yml), &idxNode)
	assert.NoError(t, mErr)
	idx := index.NewSpecIndexWithConfig(&idxNode, index.CreateClosedAPIIndexConfig())

	var n Example
	err := low.BuildModel(idxNode.Content[0], &n)
	assert.NoError(t, err)

	err = n.Build(context.Background(), nil, idxNode.Content[0], idx)
	assert.NoError(t, err)
	assert.Equal(t, "hot", n.Summary.Value)
	assert.Equal(t, "cakes", n.Description.Value)

	var a []any
	err = n.Value.Value.Decode(&a)
	require.NoError(t, err)

	assert.Equal(t, "wow", a[0])
	assert.Equal(t, "such array", a[1])
}

func TestExample_Build_Success_MergeNode(t *testing.T) {
	yml := `x-things: &things
  summary: hot
  description: cakes
  value:
    - wow
    - such array
<<: *things`

	var idxNode yaml.Node
	mErr := yaml.Unmarshal([]byte(yml), &idxNode)
	assert.NoError(t, mErr)
	idx := index.NewSpecIndexWithConfig(&idxNode, index.CreateClosedAPIIndexConfig())

	var n Example
	err := low.BuildModel(idxNode.Content[0], &n)
	assert.NoError(t, err)

	err = n.Build(context.Background(), nil, idxNode.Content[0], idx)
	assert.NoError(t, err)
	assert.Equal(t, "hot", n.Summary.Value)
	assert.Equal(t, "cakes", n.Description.Value)

	var a []any
	err = n.Value.GetValue().Decode(&a)
	require.NoError(t, err)

	assert.Equal(t, "wow", a[0])
	assert.Equal(t, "such array", a[1])
}

func TestExample_Hash(t *testing.T) {
	left := `summary: hot
description: cakes
x-burger: nice
externalValue: cake
value:
  pizza: oven
  yummy: pizza`

	right := `externalValue: cake
summary: hot
value:
  pizza: oven
  yummy: pizza
description: cakes
x-burger: nice`

	var lNode, rNode yaml.Node
	_ = yaml.Unmarshal([]byte(left), &lNode)
	_ = yaml.Unmarshal([]byte(right), &rNode)

	// create low level objects
	var lDoc Example
	var rDoc Example
	_ = low.BuildModel(lNode.Content[0], &lDoc)
	_ = low.BuildModel(rNode.Content[0], &rDoc)
	_ = lDoc.Build(context.Background(), nil, lNode.Content[0], nil)
	_ = rDoc.Build(context.Background(), nil, rNode.Content[0], nil)

	assert.Equal(t, lDoc.Hash(), rDoc.Hash())
	assert.Equal(t, 1, orderedmap.Len(lDoc.GetExtensions()))
}

func TestExample_Build_Success_Ref(t *testing.T) {
	yml := `$ref: "#/responses/abc"`

	var idxNode yaml.Node
	mErr := yaml.Unmarshal([]byte(yml), &idxNode)
	assert.NoError(t, mErr)
	idx := index.NewSpecIndexWithConfig(&idxNode, index.CreateClosedAPIIndexConfig())

	var n Example
	err := low.BuildModel(idxNode.Content[0], &n)
	assert.NoError(t, err)

	err = n.Build(context.Background(), nil, idxNode.Content[0], idx)
	assert.NoError(t, err)

	assert.True(t, n.IsReference())
	assert.Equal(t, "#/responses/abc", n.GetReference())
}

func TestExample_DataValue(t *testing.T) {
	yml := `summary: data example
description: example using dataValue
dataValue:
  name: John Doe
  age: 30
  active: true`

	var idxNode yaml.Node
	mErr := yaml.Unmarshal([]byte(yml), &idxNode)
	assert.NoError(t, mErr)
	idx := index.NewSpecIndexWithConfig(&idxNode, index.CreateClosedAPIIndexConfig())

	var n Example
	err := low.BuildModel(idxNode.Content[0], &n)
	assert.NoError(t, err)

	err = n.Build(context.Background(), nil, idxNode.Content[0], idx)
	assert.NoError(t, err)
	assert.Equal(t, "data example", n.Summary.Value)
	assert.Equal(t, "example using dataValue", n.Description.Value)
	assert.NotNil(t, n.DataValue.Value)

	var data map[string]interface{}
	err = n.DataValue.Value.Decode(&data)
	require.NoError(t, err)
	assert.Equal(t, "John Doe", data["name"])
	assert.Equal(t, 30, data["age"])
	assert.Equal(t, true, data["active"])

	// test hash includes dataValue
	hash1 := n.Hash()
	originalData := n.DataValue.Value
	n.DataValue = low.NodeReference[*yaml.Node]{} // clear the reference
	hash2 := n.Hash()
	assert.NotEqual(t, hash1, hash2)
	n.DataValue.Value = originalData // restore
}

func TestExample_SerializedValue(t *testing.T) {
	yml := `summary: serialized example
description: example using serializedValue
serializedValue: '{"name":"John Doe","age":30,"active":true}'`

	var idxNode yaml.Node
	mErr := yaml.Unmarshal([]byte(yml), &idxNode)
	assert.NoError(t, mErr)
	idx := index.NewSpecIndexWithConfig(&idxNode, index.CreateClosedAPIIndexConfig())

	var n Example
	err := low.BuildModel(idxNode.Content[0], &n)
	assert.NoError(t, err)

	err = n.Build(context.Background(), nil, idxNode.Content[0], idx)
	assert.NoError(t, err)
	assert.Equal(t, "serialized example", n.Summary.Value)
	assert.Equal(t, "example using serializedValue", n.Description.Value)
	assert.Equal(t, `{"name":"John Doe","age":30,"active":true}`, n.SerializedValue.Value)

	// test hash includes serializedValue
	hash1 := n.Hash()
	n.SerializedValue.Value = "different"
	hash2 := n.Hash()
	assert.NotEqual(t, hash1, hash2)
}

func TestExample_Build_ScalarRoot(t *testing.T) {
	var scalar yaml.Node
	require.NoError(t, yaml.Unmarshal([]byte("hello"), &scalar))

	var ex Example
	require.NoError(t, low.BuildModel(scalar.Content[0], &ex))
	require.NoError(t, ex.Build(context.Background(), nil, scalar.Content[0], nil))

	assert.NotNil(t, ex.Nodes)
	nodes := ex.GetNodes()
	assert.Len(t, nodes[scalar.Content[0].Line], 1)
	assert.Equal(t, "hello", nodes[scalar.Content[0].Line][0].Value)
}
