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

package pod

import (
	"context"
	"fmt"
	"net/http"

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

	capsulev1beta2 "github.com/projectcapsule/capsule/api/v1beta2"
	caperrors "github.com/projectcapsule/capsule/pkg/api/errors"
	"github.com/projectcapsule/capsule/pkg/api/rules"
	ad "github.com/projectcapsule/capsule/pkg/runtime/admission"
	"github.com/projectcapsule/capsule/pkg/runtime/events"
	"github.com/projectcapsule/capsule/pkg/runtime/handlers"
)

type runtimeClass struct{}

func RuntimeClass() handlers.TypedHandlerWithTenantWithRuleset[*corev1.Pod] {
	return &runtimeClass{}
}

func (h *runtimeClass) OnCreate(
	_ client.Client,
	reader client.Reader,
	pod *corev1.Pod,
	decoder admission.Decoder,
	recorder events.EventRecorder,
	tnt *capsulev1beta2.Tenant,
	_ []*rules.NamespaceRuleBodyNamespace,
) handlers.Func {
	return func(ctx context.Context, req admission.Request) *admission.Response {
		return h.validate(ctx, reader, recorder, req, pod, tnt)
	}
}

func (h *runtimeClass) OnUpdate(
	client.Client,
	client.Reader,
	*corev1.Pod,
	*corev1.Pod,
	admission.Decoder,
	events.EventRecorder,
	*capsulev1beta2.Tenant,
	[]*rules.NamespaceRuleBodyNamespace,
) handlers.Func {
	return func(context.Context, admission.Request) *admission.Response {
		return nil
	}
}

func (h *runtimeClass) OnDelete(
	client.Client,
	client.Reader,
	*corev1.Pod,
	admission.Decoder,
	events.EventRecorder,
	*capsulev1beta2.Tenant,
	[]*rules.NamespaceRuleBodyNamespace,
) handlers.Func {
	return func(context.Context, admission.Request) *admission.Response {
		return nil
	}
}

func (h *runtimeClass) class(ctx context.Context, c client.Reader, name string) (client.Object, error) {
	if len(name) == 0 {
		return nil, nil
	}

	obj := &nodev1.RuntimeClass{}
	if err := c.Get(ctx, types.NamespacedName{Name: name}, obj); err != nil {
		return nil, err
	}

	return obj, nil
}

func (h *runtimeClass) validate(
	ctx context.Context,
	c client.Reader,
	recorder events.EventRecorder,
	req admission.Request,
	pod *corev1.Pod,
	tnt *capsulev1beta2.Tenant,
) *admission.Response {
	allowed := tnt.Spec.RuntimeClasses

	runtimeClassName := ""
	if pod.Spec.RuntimeClassName != nil {
		runtimeClassName = *pod.Spec.RuntimeClassName
	}

	class, err := h.class(ctx, c, runtimeClassName)
	if err != nil {
		response := admission.Errored(http.StatusInternalServerError, err)

		return &response
	}

	switch {
	case allowed == nil:
		// Enforcement is not in place, skipping it at all
		return nil
	case len(runtimeClassName) == 0 || runtimeClassName == allowed.Default:
		// Delegating mutating webhook to specify a default RuntimeClass
		return nil
	case !allowed.MatchSelectByName(class):
		recorder.LabeledEvent(
			pod,
			corev1.EventTypeWarning,
			events.ReasonForbiddenRuntimeClass,
			events.ActionValidationDenied,
			fmt.Sprintf("using runtimeclass %s is forbidden for the tenant", runtimeClassName),
		).
			WithRelated(tnt).
			WithTenantLabel(tnt).
			WithRequestAnnotations(req).
			Emit(ctx)

		return ad.Deny(caperrors.NewPodRuntimeClassForbidden(runtimeClassName, *allowed).Error())
	default:
		return nil
	}
}
