package agent

import (
	"fmt"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modshared"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/starboard_vulnerability"
)

const (
	defaultGitlabAgentNamespace      = "gitlab-agent"
	defaultGitlabAgentServiceAccount = "gitlab-agent"
)

type Factory struct{}

func (f *Factory) New(cfg *modagent.Config) (modagent.Module, error) {
	kubeClientset, err := cfg.K8sUtilFactory.KubernetesClientSet()
	if err != nil {
		return nil, fmt.Errorf("could not create kubernetes clientset: %w", err)
	}
	return &module{
		log:                       cfg.Log,
		api:                       cfg.Api,
		policiesUpdateDataChannel: make(chan configurationToUpdateData),
		workerFactory: (&workerFactory{
			log:                       cfg.Log,
			api:                       cfg.Api,
			kubeClientset:             kubeClientset,
			gitlabAgentNamespace:      getAgentNamespace(cfg),
			gitlabAgentServiceAccount: getAgentServiceAccount(cfg),
		}).New,
	}, nil
}

func (f *Factory) Name() string {
	return starboard_vulnerability.ModuleName
}

func (f *Factory) StartStopPhase() modshared.ModuleStartStopPhase {
	return modshared.ModuleStartBeforeServers
}

func getAgentNamespace(cfg *modagent.Config) string {
	namespace := cfg.AgentMeta.PodNamespace
	if namespace == "" {
		namespace = defaultGitlabAgentNamespace
	}
	return namespace
}

func getAgentServiceAccount(cfg *modagent.Config) string {
	serviceAccountName := cfg.ServiceAccountName
	if serviceAccountName == "" {
		serviceAccountName = defaultGitlabAgentServiceAccount
	}
	return serviceAccountName
}
