package managed_resources //nolint:staticcheck

import (
	"testing"

	"buf.build/go/protovalidate"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"sigs.k8s.io/yaml"
)

func TestRenderer_renderObject(t *testing.T) {
	// GIVEN
	template := []byte(`
apiVersion: v1
kind: Namespace
metadata:
  name: '{{ .environment.slug }}-{{ .project.id }}-{{ .agent.id }}'
`)
	expectedRendered := []byte(`
apiVersion: v1
kind: Namespace
metadata:
  name: 'any-slug-1-2'
`)

	// WHEN
	u, err := renderObject(template, map[string]any{
		"environment": map[string]any{
			"slug": "any-slug",
		},
		"project": map[string]any{
			"id": 1,
		},
		"agent": map[string]any{
			"id": 2,
		},
	})
	require.NoError(t, err)

	// THEN
	actualRendered, err := yaml.Marshal(u.Object)
	require.NoError(t, err)

	assert.YAMLEq(t, string(expectedRendered), string(actualRendered))
}

func TestRenderer_renderObject_funcs(t *testing.T) {
	// GIVEN
	template := []byte(`
apiVersion: v1
kind: Namespace
metadata:
  name: '{{ .environment.slug | lower }}-{{ .project.id }}-{{ .agent.id }}'
`)
	expectedRendered := []byte(`
apiVersion: v1
kind: Namespace
metadata:
  name: 'any-slug-1-2'
`)

	// WHEN
	u, err := renderObject(template, map[string]any{
		"environment": map[string]any{
			"slug": "ANY-SLUG",
		},
		"project": map[string]any{
			"id": 1,
		},
		"agent": map[string]any{
			"id": 2,
		},
	})
	require.NoError(t, err)

	// THEN
	actualRendered, err := yaml.Marshal(u.Object)
	require.NoError(t, err)

	assert.YAMLEq(t, string(expectedRendered), string(actualRendered))
}

func TestRenderer_ExtractEnvironmentInfosFromObject_withoutOptionalEnvironmentInfo(t *testing.T) {
	// GIVEN
	tests := []struct {
		name string
		info *EnvironmentInfo
	}{
		{
			name: "",
			info: &EnvironmentInfo{
				EnvironmentId:   42,
				EnvironmentName: "any",
				EnvironmentSlug: "any",
				// EnvironmentUrl:
				EnvironmentPageUrl: "any",
				EnvironmentTier:    "any",
				AgentId:            1,
				AgentName:          "any",
				AgentUrl:           "any",
				ProjectId:          2,
				ProjectSlug:        "any",
				ProjectPath:        "any",
				ProjectUrl:         "any",
				TemplateName:       "any",
				// LegacyNamespace: "",
			},
		},
	}

	v, err := protovalidate.New()
	require.NoError(t, err)
	r := Renderer{Validator: v}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// GIVEN
			obj := unstructured.Unstructured{}
			setEnvironmentInfoOnObjects([]unstructured.Unstructured{obj}, tt.info)

			// WHEN
			_, err := r.ExtractEnvironmentInfosFromObject(&obj)

			// THEN
			require.NoError(t, err)
		})
	}
}
