package watch_graph //nolint:staticcheck

import (
	networkingv1 "k8s.io/api/networking/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/utils/ptr"
)

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

	if o.Spec.IngressClassName != nil {
		vx.setArcToGVK(ingressClassGVK, *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.setArcToGVK(secretGVK, 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.setArcToGVK(serviceGVK, b.Service.Name, ArcAttrs{}, arcType)
	case b.Resource != nil:
		vx.setArcTo(ptr.Deref(b.Resource.APIGroup, ""), b.Resource.Kind, b.Resource.Name, "", ArcAttrs{}, arcType)
	}
}
