package watch_graph //nolint:staticcheck

import (
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/cli-runtime/pkg/resource"
)

type vertexGKID struct {
	GK schema.GroupKind
	// The namespace to use if object is namespaced and the source object's namespace should not be used.
	NamespaceOverride string
	Name              string
}

// wgObject2vertex collects vertex and arc data for a Kubernetes object.
// Instances are not reusable.
type wgObject2vertex struct {
	gvr        schema.GroupVersionResource
	info       gvrInfo
	newBuilder func() *resource.Builder

	// Fields below accumulate results for Get().
	ns       string // empty or namespace of the object
	name     string // name of the object
	vd       VertexData
	arcSet   ArcSetWithData[vertexGKID, ArcType, ArcAttrs]
	warnings []Warning
}

func newObject2vertex(gvr schema.GroupVersionResource, info gvrInfo, newBuilder func() *resource.Builder) *wgObject2vertex {
	return &wgObject2vertex{
		gvr:        gvr,
		info:       info,
		newBuilder: newBuilder,
	}
}

func (vx *wgObject2vertex) Get(obj *unstructured.Unstructured) (VertexData, ArcSetWithData[vertexGKID, ArcType, ArcAttrs], []Warning, *Error) {
	// 1. Must set ns and name first since they are used to construct warnings
	vx.ns = obj.GetNamespace()
	vx.name = obj.GetName()
	vx.vd = VertexData{
		Object:   obj.Object,
		JSONPath: vx.info.object.JSONPath,
	}

	// 2. Process object
	vx.collectOwnerReferencesArcs(obj)
	err := vx.kindSpecificProcessing(obj)
	if err != nil {
		return VertexData{}, nil, vx.warnings, err
	}

	return vx.vd, vx.arcSet, vx.warnings, nil
}

func (vx *wgObject2vertex) appendObjectProcessingWarning(message string) {
	vx.warnings = append(vx.warnings, NewObjectProcessingWarning(vx.gvr, vx.ns, vx.name, message))
}
