package watch_graph //nolint:staticcheck

import (
	autoscalingv1 "gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/kubernetes_api/agentk/watch_graph/vendored/k8s.io/api/autoscaling/v1"
	autoscalingv2 "gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/kubernetes_api/agentk/watch_graph/vendored/k8s.io/api/autoscaling/v2"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

func (vx *wgObject2vertex) collectHorizontalPodAutoscalerV1(obj *unstructured.Unstructured) *Error {
	o, errX := unstructuredToTyped[autoscalingv1.HorizontalPodAutoscaler](obj)
	if errX != nil {
		return errX
	}

	gv, err := schema.ParseGroupVersion(o.Spec.ScaleTargetRef.APIVersion)
	if err != nil {
		vx.appendObjectProcessingWarning(err.Error())
		return nil
	}

	vx.setArcTo(gv.Group, o.Spec.ScaleTargetRef.Kind, o.Spec.ScaleTargetRef.Name, "", ArcAttrs{}, ReferenceArcType)
	return nil
}

func (vx *wgObject2vertex) collectHorizontalPodAutoscalerV2(obj *unstructured.Unstructured) *Error {
	o, errX := unstructuredToTyped[autoscalingv2.HorizontalPodAutoscaler](obj)
	if errX != nil {
		return errX
	}

	gv, err := schema.ParseGroupVersion(o.Spec.ScaleTargetRef.APIVersion)
	if err != nil {
		vx.appendObjectProcessingWarning(err.Error())
	} else {
		vx.setArcTo(gv.Group, o.Spec.ScaleTargetRef.Kind, o.Spec.ScaleTargetRef.Name, "", ArcAttrs{}, ReferenceArcType)
	}

	collectEach(o.Spec.Metrics, ReferenceArcType, func(m *autoscalingv2.MetricSpec, arcType ArcType) {
		if m.Object == nil {
			return
		}
		gv, err := schema.ParseGroupVersion(m.Object.DescribedObject.APIVersion)
		if err != nil {
			vx.appendObjectProcessingWarning(err.Error())
		} else {
			vx.setArcTo(gv.Group, m.Object.DescribedObject.Kind, m.Object.DescribedObject.Name, "", ArcAttrs{}, ReferenceArcType)
		}
	})

	return nil
}
