// Copyright 2022 Camunda Services GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package camunda

import (
	"path/filepath"
	"strings"
	"testing"

	"github.com/gruntwork-io/terratest/modules/helm"
	"github.com/gruntwork-io/terratest/modules/k8s"
	"github.com/gruntwork-io/terratest/modules/random"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
	coreV1 "k8s.io/api/core/v1"
)

type secretTest struct {
	suite.Suite
	chartPath  string
	release    string
	namespace  string
	templates  []string
	secretName []string
}

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

	chartPath, err := filepath.Abs("../../../")
	require.NoError(t, err)

	suite.Run(t, &secretTest{
		chartPath:  chartPath,
		release:    "camunda-platform-test",
		namespace:  "camunda-platform-" + strings.ToLower(random.UniqueId()),
		templates:  []string{},
		secretName: []string{},
	})
}

func (s *secretTest) TestSecretNotGeneratedWhenAutoGenDisabled() {
	// given
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated": "false",
		},
	}

	// when
	output, err := helm.RenderTemplateE(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})

	// then
	s.Require().Error(err)
	s.Require().Contains(err.Error(), "could not find template")
	s.Require().Empty(output)
}

func (s *secretTest) TestSecretGeneratedWithAutoGenEnabled() {
	// given
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated": "true",
		},
	}

	// when
	output := helm.RenderTemplate(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})
	var secret coreV1.Secret
	helm.UnmarshalK8SYaml(s.T(), output, &secret)

	// then
	s.Require().Equal("Secret", secret.Kind)
	s.Require().Equal("v1", secret.APIVersion)
	s.Require().Equal("camunda-credentials", secret.Name)
	s.Require().Equal("Opaque", string(secret.Type))

	// Check annotations
	s.Require().Contains(secret.Annotations, "helm.sh/hook")
	s.Require().Equal("pre-install", secret.Annotations["helm.sh/hook"])
	s.Require().Contains(secret.Annotations, "helm.sh/resource-policy")
	s.Require().Equal("keep", secret.Annotations["helm.sh/resource-policy"])
}

func (s *secretTest) TestSecretContainsIdentityAuthTokens() {
	// given
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated": "true",
			"global.identity.auth.enabled":  "true",
		},
	}

	// when
	output := helm.RenderTemplate(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})
	var secret coreV1.Secret
	helm.UnmarshalK8SYaml(s.T(), output, &secret)

	// then
	expectedTokens := []string{
		"identity-admin-client-token",
		"identity-connectors-client-token",
		"identity-console-client-token",
		"identity-orchestration-client-token",
		"identity-optimize-client-token",
	}

	for _, tokenKey := range expectedTokens {
		s.Require().Contains(secret.Data, tokenKey, "Secret should contain %s", tokenKey)
		s.Require().NotEmpty(secret.Data[tokenKey], "Token %s should not be empty", tokenKey)
	}
}

func (s *secretTest) TestSecretContainsIdentityFirstUserPassword() {
	// given
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated": "true",
			// Enable identity auth so that the first user password gets generated
			"global.identity.auth.enabled": "true",
		},
	}

	// when
	output := helm.RenderTemplate(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})
	var secret coreV1.Secret
	helm.UnmarshalK8SYaml(s.T(), output, &secret)

	// then
	s.Require().Contains(secret.Data, "identity-firstuser-password")
	s.Require().NotEmpty(secret.Data["identity-firstuser-password"])
}

func (s *secretTest) TestSecretContainsKeycloakAdminPassword() {
	// given
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated": "true",
			"global.identity.auth.enabled":  "true",
		},
	}

	// when
	output := helm.RenderTemplate(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})
	var secret coreV1.Secret
	helm.UnmarshalK8SYaml(s.T(), output, &secret)

	// then
	s.Require().Contains(secret.Data, "identity-keycloak-admin-password")
	s.Require().NotEmpty(secret.Data["identity-keycloak-admin-password"])
}

func (s *secretTest) TestSecretContainsPostgreSQLPasswords() {
	// given
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated": "true",
		},
	}

	// when
	output := helm.RenderTemplate(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})
	var secret coreV1.Secret
	helm.UnmarshalK8SYaml(s.T(), output, &secret)

	// then
	// Identity PostgreSQL passwords
	s.Require().Contains(secret.Data, "identity-postgresql-admin-password")
	s.Require().NotEmpty(secret.Data["identity-postgresql-admin-password"])
	s.Require().Contains(secret.Data, "identity-postgresql-user-password")
	s.Require().NotEmpty(secret.Data["identity-postgresql-user-password"])

	// Keycloak PostgreSQL passwords
	s.Require().Contains(secret.Data, "identity-keycloak-postgresql-admin-password")
	s.Require().NotEmpty(secret.Data["identity-keycloak-postgresql-admin-password"])
	s.Require().Contains(secret.Data, "identity-keycloak-postgresql-user-password")
	s.Require().NotEmpty(secret.Data["identity-keycloak-postgresql-user-password"])

	// Web Modeler PostgreSQL passwords
	s.Require().Contains(secret.Data, "web-modeler-postgresql-admin-password")
	s.Require().NotEmpty(secret.Data["web-modeler-postgresql-admin-password"])
	s.Require().Contains(secret.Data, "web-modeler-postgresql-user-password")
	s.Require().NotEmpty(secret.Data["web-modeler-postgresql-user-password"])
}

func (s *secretTest) TestSecretWithCustomName() {
	// given
	customSecretName := "my-custom-secret"
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated": "true",
			"global.secrets.name":          customSecretName,
		},
	}

	// when
	output := helm.RenderTemplate(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})
	var secret coreV1.Secret
	helm.UnmarshalK8SYaml(s.T(), output, &secret)

	// then
	s.Require().Equal(customSecretName, secret.Name)
}

func (s *secretTest) TestSecretWithCustomAnnotations() {
	// given
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated":                      "true",
			"global.secrets.annotations.custom\\.annotation":   "custom-value",
			"global.secrets.annotations.another\\.annotation":  "another-value",
		},
	}

	// when
	output := helm.RenderTemplate(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})
	var secret coreV1.Secret
	helm.UnmarshalK8SYaml(s.T(), output, &secret)

	// then
	s.Require().Contains(secret.Annotations, "custom.annotation")
	s.Require().Equal("custom-value", secret.Annotations["custom.annotation"])
	s.Require().Contains(secret.Annotations, "another.annotation")
	s.Require().Equal("another-value", secret.Annotations["another.annotation"])

	// Default annotations should still be present
	s.Require().Contains(secret.Annotations, "helm.sh/hook")
	s.Require().Contains(secret.Annotations, "helm.sh/resource-policy")
}

func (s *secretTest) TestSecretGenerationDependsOnConfiguration() {
	// given - test that auth tokens are only generated when identity auth is enabled
	options := &helm.Options{
		KubectlOptions: k8s.NewKubectlOptions("", "", s.namespace),
		SetValues: map[string]string{
			"global.secrets.autoGenerated":  "true",
			"global.identity.auth.enabled":  "false", // Explicitly disable auth
		},
	}

	// when
	output := helm.RenderTemplate(s.T(), options, s.chartPath, s.release, []string{"templates/common/secret-camunda.yaml"})
	var secret coreV1.Secret
	helm.UnmarshalK8SYaml(s.T(), output, &secret)

	// then - auth tokens should not be present
	s.Require().NotContains(secret.Data, "identity-admin-client-token")
	s.Require().NotContains(secret.Data, "identity-connectors-client-token")
	s.Require().NotContains(secret.Data, "identity-console-client-token")
	s.Require().NotContains(secret.Data, "identity-orchestration-client-token")
	s.Require().NotContains(secret.Data, "identity-optimize-client-token")

	// but PostgreSQL passwords should still be present
	s.Require().Contains(secret.Data, "identity-postgresql-admin-password")
	s.Require().Contains(secret.Data, "identity-postgresql-user-password")
}


