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

package generic

import (
	"context"
	"fmt"

	"github.com/pkg/errors"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/util/retry"
	"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/tenant"
)

type resourceCounterHandler struct {
	client client.Client
}

func ResourceCounterHandler(client client.Client) handlers.Handler {
	return &resourceCounterHandler{
		client: client,
	}
}

func (r *resourceCounterHandler) OnCreate(
	c client.Client,
	reader client.Reader,
	_ admission.Decoder,
	recorder events.EventRecorder,
) handlers.Func {
	return func(ctx context.Context, req admission.Request) *admission.Response {
		var tntName string

		var err error
		if tntName, err = r.getTenantName(ctx, c, req); err != nil {
			return ad.ErroredResponse(err)
		}

		if len(tntName) == 0 {
			return nil
		}

		kgv := fmt.Sprintf("%s.%s_%s", req.Resource.Resource, req.Resource.Group, req.Resource.Version)

		tnt := &capsulev1beta2.Tenant{}

		var limit int64

		err = retry.RetryOnConflict(retry.DefaultRetry, func() (retryErr error) {
			if retryErr = reader.Get(ctx, types.NamespacedName{Name: tntName}, tnt); err != nil {
				return retryErr
			}

			if limit, retryErr = capsulev1beta2.GetLimitResourceFromTenant(*tnt, kgv); retryErr != nil {
				if errors.As(err, &capsulev1beta2.NonLimitedResourceError{}) {
					return nil
				}

				return err
			}

			used, _ := capsulev1beta2.GetUsedResourceFromTenant(*tnt, kgv)
			if used >= limit {
				return caperrors.NewCustomResourceQuotaError(kgv, limit)
			}

			tnt.Annotations[capsulev1beta2.UsedAnnotationForResource(kgv)] = fmt.Sprintf("%d", used+1)

			return c.Update(ctx, tnt)
		})
		if err != nil {
			if errors.As(err, &caperrors.CustomResourceQuotaError{}) {
				recorder.LabeledEvent(
					tnt,
					corev1.EventTypeWarning,
					events.ReasonOverprovision,
					events.ActionValidationDenied,
					fmt.Sprintf("Resource %s/%s in API group %s cannot be created, limit usage of %d has been reached", req.Namespace, req.Name, kgv, limit),
				).
					WithRelated(tnt).
					WithTenantLabel(tnt).
					WithRequestAnnotations(req).
					Emit(ctx)
			}

			return ad.ErroredResponse(err)
		}

		return nil
	}
}

func (r *resourceCounterHandler) OnDelete(
	c client.Client,
	reader client.Reader,
	_ admission.Decoder,
	_ events.EventRecorder,
) handlers.Func {
	return func(ctx context.Context, req admission.Request) *admission.Response {
		var tntName string

		var err error
		if tntName, err = r.getTenantName(ctx, c, req); err != nil {
			return ad.ErroredResponse(err)
		}

		if len(tntName) == 0 {
			return nil
		}

		kgv := fmt.Sprintf("%s.%s_%s", req.Resource.Resource, req.Resource.Group, req.Resource.Version)

		err = retry.RetryOnConflict(retry.DefaultRetry, func() (retryErr error) {
			tnt := &capsulev1beta2.Tenant{}
			if retryErr = reader.Get(ctx, types.NamespacedName{Name: tntName}, tnt); err != nil {
				return retryErr
			}

			if tnt.Annotations == nil {
				return retryErr
			}

			if _, ok := tnt.Annotations[capsulev1beta2.UsedAnnotationForResource(kgv)]; !ok {
				return retryErr
			}

			used, _ := capsulev1beta2.GetUsedResourceFromTenant(*tnt, kgv)

			tnt.Annotations[capsulev1beta2.UsedAnnotationForResource(kgv)] = fmt.Sprintf("%d", used-1)

			return c.Update(ctx, tnt)
		})
		if err != nil {
			return ad.ErroredResponse(err)
		}

		return nil
	}
}

func (r *resourceCounterHandler) OnUpdate(
	client.Client,
	client.Reader,
	admission.Decoder,
	events.EventRecorder,
) handlers.Func {
	return func(context.Context, admission.Request) *admission.Response {
		return nil
	}
}

func (r *resourceCounterHandler) getTenantName(
	ctx context.Context,
	clt client.Client,
	req admission.Request,
) (string, error) {
	tnt, err := tenant.TenantByStatusNamespace(ctx, clt, req.Namespace)
	if err != nil {
		return "", err
	}

	if tnt == nil {
		return "", nil
	}

	return tnt.GetName(), nil
}
