package kubernetes

import (
	"github.com/ckotzbauer/vulnerability-operator/internal/vuln/kubernetes"
	"github.com/ckotzbauer/vulnerability-operator/internal/vuln/source"
	"github.com/sirupsen/logrus"
)

type KubernetesSource struct {
	images                 []source.ScanItem
	namespaceLabelSelector string
	podLabelSelector       string
}

func NewKubernetesSource(namespaceLabelSelector, podLabelSelector string) *KubernetesSource {
	return &KubernetesSource{
		images:                 []source.ScanItem{},
		namespaceLabelSelector: namespaceLabelSelector,
		podLabelSelector:       podLabelSelector,
	}
}

func (g *KubernetesSource) ValidateConfig() error {
	return nil
}

func (g *KubernetesSource) Initialize() error {
	return nil
}

func (g *KubernetesSource) LoadScanItems() []source.ScanItem {
	g.images = []source.ScanItem{}
	client := kubernetes.NewClient()

	namespaces, err := client.Client.ListNamespaces(g.namespaceLabelSelector)
	if err != nil {
		logrus.WithError(err).Error("Failed to list namespaces")
		return g.images
	}

	pods := client.Client.LoadPodInfos(namespaces, g.podLabelSelector)
	imageIds := make(map[string]bool, 0)

	for _, p := range pods {
		for _, c := range p.Containers {
			if _, ok := imageIds[c.Image.ImageID]; !ok {
				imageIds[c.Image.ImageID] = true
				g.images = append(g.images, source.Image{RegistryImage: *c.Image})
			}

		}
	}

	return g.images
}
