package watch_graph //nolint:staticcheck

import (
	"unique"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/util/workqueue"
)

type resourceEventHandler struct {
	workqueue workqueue.TypedRateLimitingInterface[VertexID]
	gvr       unique.Handle[schema.GroupVersionResource]
}

func (h *resourceEventHandler) OnAdd(obj any, isInInitialList bool) {
	h.enqueue(obj)
}

func (h *resourceEventHandler) OnUpdate(oldObj, newObj any) {
	h.enqueue(newObj)
}

func (h *resourceEventHandler) OnDelete(obj any) {
	if x, ok := obj.(cache.DeletedFinalStateUnknown); ok {
		obj = x.Obj
	}
	h.enqueue(obj)
}

func (h *resourceEventHandler) enqueue(obj any) {
	o := obj.(*unstructured.Unstructured)
	h.workqueue.Add(VertexID{
		GVR:       h.gvr,
		Namespace: o.GetNamespace(),
		Name:      o.GetName(),
	})
}
