/*


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 v1beta1

import (
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/validation/field"
	ctrl "sigs.k8s.io/controller-runtime"
	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/webhook"
	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

	"gitlab.com/gitlab-org/cloud-native/gitlab-operator/helm"
)

// log is for logging in this package.
var gitlablog = logf.Log.WithName("gitlab-resource")

// SetupWebhookWithManager adds webhook to the controller runtime Manager.
func (r *GitLab) SetupWebhookWithManager(mgr ctrl.Manager) error {
	return ctrl.NewWebhookManagedBy(mgr).
		For(r).
		Complete()
}

// +kubebuilder:webhook:verbs=create;update,path=/validate-apps-gitlab-com-v1beta1-gitlab,mutating=false,failurePolicy=fail,groups=apps.gitlab.com,resources=gitlabs,versions=v1beta1,name=vgitlab.kb.io,admissionReviewVersions=v1,sideEffects=None

var _ webhook.Validator = &GitLab{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
func (r *GitLab) ValidateCreate() (warnings admission.Warnings, err error) {
	gitlablog.Info("validate create", "name", r.Name)

	if validateErr := r.validateChartVersion(); validateErr != nil {
		err = newError(r.Name, validateErr)
		return
	}

	return
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type.
func (r *GitLab) ValidateUpdate(old runtime.Object) (warnings admission.Warnings, err error) {
	gitlablog.Info("validate update", "name", r.Name)

	if validateErr := r.validateChartVersion(); validateErr != nil {
		err = newError(r.Name, validateErr)
		return
	}

	return
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
func (r *GitLab) ValidateDelete() (warnings admission.Warnings, err error) {
	gitlablog.Info("validate delete", "name", r.Name)

	return
}

func (r GitLab) validateChartVersion() *field.Error {
	key := field.NewPath("spec").Child("chart").Child("version")
	value := r.Spec.Chart.Version

	if value == "" {
		return field.Invalid(key, value, "chart version must be configured")
	}

	if _, err := helm.ChartVersionSupported(r.Spec.Chart.Version); err != nil {
		return field.Invalid(key, value, err.Error())
	}

	return nil
}

func newError(name string, err *field.Error) error {
	return apierrors.NewInvalid(GroupKind, name, field.ErrorList{err})
}
