package watch_graph //nolint:staticcheck

import (
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/kubernetes_api/agent/watch_graph/vendored/k8s.io/api/core"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/kubernetes_api/agent/watch_graph/vendored/k8s.io/api/networking"
	networkingv1 "gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/kubernetes_api/agent/watch_graph/vendored/k8s.io/api/networking/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/utils/ptr"
)

func (vx *wgObject2vertex) collectIngressV1(obj *unstructured.Unstructured) *Error {
	o, err := unstructuredToTyped[networkingv1.Ingress](obj)
	if err != nil {
		return err
	}

	if o.Spec.IngressClassName != nil {
		vx.setArcToGK(networking.IngressClassGK, *o.Spec.IngressClassName, ArcAttrs{}, ReferenceArcType)
	}

	if o.Spec.DefaultBackend != nil {
		vx.collectIngressBackendV1Arcs(o.Spec.DefaultBackend, ReferenceArcType)
	}

	collectEach(o.Spec.TLS, ReferenceArcType, func(t *networkingv1.IngressTLS, arcType ArcType) {
		if t.SecretName == "" {
			return
		}
		vx.setArcToSecret(t.SecretName, ArcAttrs{}, ReferenceArcType)
	})

	collectEach(o.Spec.Rules, ReferenceArcType, func(r *networkingv1.IngressRule, arcType ArcType) {
		if r.HTTP == nil {
			return
		}
		collectEach(r.HTTP.Paths, arcType, func(p *networkingv1.HTTPIngressPath, arcType ArcType) {
			vx.collectIngressBackendV1Arcs(&p.Backend, arcType)
		})
	})

	return nil
}

func (vx *wgObject2vertex) collectIngressBackendV1Arcs(b *networkingv1.IngressBackend, arcType ArcType) {
	switch { // only one is set
	case b.Service != nil:
		vx.setArcToGK(core.ServiceGK, b.Service.Name, ArcAttrs{}, arcType)
	case b.Resource != nil:
		vx.setArcTo(ptr.Deref(b.Resource.APIGroup, ""), b.Resource.Kind, b.Resource.Name, "", ArcAttrs{}, arcType)
	}
}
