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

package validation

import (
	"context"

	corev1 "k8s.io/api/core/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"
	ad "github.com/projectcapsule/capsule/pkg/runtime/admission"
	"github.com/projectcapsule/capsule/pkg/runtime/events"
	"github.com/projectcapsule/capsule/pkg/runtime/handlers"
	"github.com/projectcapsule/capsule/pkg/users"
)

type quotaHandler struct{}

func QuotaHandler() handlers.TypedHandlerWithTenantUser[*corev1.Namespace] {
	return &quotaHandler{}
}

func (h *quotaHandler) OnCreate(
	_ client.Client,
	reader client.Reader,
	_ users.AdmissionUser,
	ns *corev1.Namespace,
	_ admission.Decoder,
	recorder events.EventRecorder,
	tnt *capsulev1beta2.Tenant,
) handlers.Func {
	return func(ctx context.Context, req admission.Request) *admission.Response {
		return h.handle(ctx, req, reader, recorder, ns, tnt)
	}
}

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

func (h *quotaHandler) OnUpdate(
	_ client.Client,
	reader client.Reader,
	_ users.AdmissionUser,
	ns *corev1.Namespace,
	_ *corev1.Namespace,
	_ admission.Decoder,
	recorder events.EventRecorder,
	tnt *capsulev1beta2.Tenant,
) handlers.Func {
	return func(ctx context.Context, req admission.Request) *admission.Response {
		return h.handle(ctx, req, reader, recorder, ns, tnt)
	}
}

func (h *quotaHandler) handle(
	ctx context.Context,
	req admission.Request,
	c client.Reader,
	recorder events.EventRecorder,
	ns *corev1.Namespace,
	tnt *capsulev1beta2.Tenant,
) *admission.Response {
	if tnt.IsFull() {
		// Checking if the Namespace already exists.
		// If this is the case, no need to return the quota exceeded error:
		// the Kubernetes API Server will return an AlreadyExists error,
		// adhering more to the native Kubernetes experience.
		if err := c.Get(ctx, types.NamespacedName{Name: ns.Name}, &corev1.Namespace{}); err == nil {
			return nil
		}

		recorder.LabeledEvent(
			ns,
			corev1.EventTypeWarning,
			events.ReasonOverprovision,
			events.ActionValidationDenied,
			"namespace cannot be attached, quota exceeded for the elected tenant",
		).
			WithRelated(tnt).
			WithTenantLabel(tnt).
			WithRequestAnnotations(req).
			Emit(ctx)

		return ad.Deny(caperrors.NewNamespaceQuotaExceededError().Error())
	}

	return nil
}
