package v1

import (
	"context"

	"k8s.io/apimachinery/pkg/api/equality"
	"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/admission"
)

var configRevisionLogger = logf.Log.WithName("configrevision-resource")
var _ admission.Validator = &ConfigRevision{}
var _ admission.Defaulter = &ConfigRevision{}

// +kubebuilder:webhook:path=/mutate-cloud-pingcap-com-v1-configrevision,mutating=true,failurePolicy=fail,sideEffects=None,groups=cloud.pingcap.com,resources=configrevisions,verbs=create;update,versions=v1,name=mconfigrevision.kb.io,admissionReviewVersions={v1,v1beta1}
// +kubebuilder:webhook:path=/validate-cloud-pingcap-com-v1-configrevision,mutating=false,failurePolicy=fail,sideEffects=None,groups=cloud.pingcap.com,resources=configrevisions,verbs=create;update,versions=v1,name=vconfigrevision.kb.io,admissionReviewVersions={v1,v1beta1}

func (c *ConfigRevision) setupWebhookWithManager(mgr ctrl.Manager) error {
	return ctrl.NewWebhookManagedBy(mgr).
		For(c).
		Complete()
}

// Default implements webhook.Defaulter so a webhook will be registered for the type
func (c *ConfigRevision) Default() {
	configRevisionLogger.Info("default", "name", c.Name)
	if c.Labels == nil {
		c.Labels = map[string]string{}
	}
}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (c *ConfigRevision) ValidateCreate() (warnings admission.Warnings, err error) {
	logger := configRevisionLogger.WithValues("name", c.Name)
	logger.Info("validate create")
	ctx := context.Background()
	var allErrs field.ErrorList
	if errs := c.validateSpec(ctx); errs != nil {
		allErrs = append(allErrs, errs...)
	}

	logger.Info("validate create result", "suc", len(allErrs) == 0)
	return nil, invalidOrNil(allErrs, c)
}

func (c *ConfigRevision) validateSpec(ctx context.Context) field.ErrorList {
	var allErrs field.ErrorList
	return allErrs
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (c *ConfigRevision) ValidateUpdate(old runtime.Object) (warnings admission.Warnings, err error) {
	configRevisionLogger.Info("validate update", "name", c.Name)
	oldCC, _ := old.(*ConfigRevision)
	var allErrs field.ErrorList
	if !equality.Semantic.DeepEqual(c.Spec, oldCC.Spec) {
		allErrs = append(allErrs, field.Invalid(field.NewPath("spec"), c.Spec, "field is immutable"))
	}

	return nil, invalidOrNil(allErrs, c)
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (c *ConfigRevision) ValidateDelete() (warnings admission.Warnings, err error) {
	configRevisionLogger.Info("validate delete", "name", c.Name)
	return nil, nil
}
