// Copyright 2020-2026 Project Capsule Authors
// SPDX-License-Identifier: Apache-2.0

package validation

import (
	"context"

	corev1 "k8s.io/api/core/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

	capsulev1beta2 "github.com/projectcapsule/capsule/api/v1beta2"
	"github.com/projectcapsule/capsule/pkg/runtime/events"
	"github.com/projectcapsule/capsule/pkg/runtime/handlers"
)

type freezedEmitterHandler struct{}

func FreezedEmitter() handlers.TypedHandler[*capsulev1beta2.Tenant] {
	return &freezedEmitterHandler{}
}

func (h *freezedEmitterHandler) OnCreate(
	client.Client,
	client.Reader,
	*capsulev1beta2.Tenant,
	admission.Decoder,
	events.EventRecorder,
) handlers.Func {
	return func(context.Context, admission.Request) *admission.Response {
		return nil
	}
}

func (h *freezedEmitterHandler) OnDelete(
	client.Client,
	client.Reader,
	*capsulev1beta2.Tenant,
	admission.Decoder,
	events.EventRecorder,
) handlers.Func {
	return func(context.Context, admission.Request) *admission.Response {
		return nil
	}
}

func (h *freezedEmitterHandler) OnUpdate(
	_ client.Client,
	_ client.Reader,
	tnt *capsulev1beta2.Tenant,
	old *capsulev1beta2.Tenant,
	decoder admission.Decoder,
	recorder events.EventRecorder,
) handlers.Func {
	return func(ctx context.Context, req admission.Request) *admission.Response {
		switch {
		case !old.Spec.Cordoned && tnt.Spec.Cordoned:
			recorder.LabeledEvent(
				tnt,
				corev1.EventTypeNormal,
				events.ReasonCordoning,
				events.ActionCordoned,
				"Tenant has been cordoned",
			).
				WithTenantLabel(tnt).
				WithRequestAnnotations(req).
				Emit(ctx)
		case old.Spec.Cordoned && !tnt.Spec.Cordoned:
			recorder.LabeledEvent(
				tnt,
				corev1.EventTypeNormal,
				events.ReasonCordoning,
				events.ActionUncordoned,
				"Tenant has been uncordoned",
			).
				WithTenantLabel(tnt).
				WithRequestAnnotations(req).
				Emit(ctx)
		}

		return nil
	}
}
