//go:build !fips

package agent

import (
	"fmt"
	"os"
	"strconv"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modagentk"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/starboard_vulnerability"
)

const (
	envVarOcsServiceAccountName = "OCS_SERVICE_ACCOUNT_NAME"
	envVarOcsEnabled            = "OCS_ENABLED"
)

type Factory struct{}

func (f *Factory) IsProducingLeaderModules() bool {
	return true
}

func (f *Factory) New(cfg *modagentk.Config) (modagentk.Module, error) {
	// In case of an error ocsEnabled is already false
	ocsEnabled, _ := strconv.ParseBool(os.Getenv(envVarOcsEnabled))
	if !ocsEnabled {
		cfg.Log.Info(fmt.Sprintf("Module is disabled. Set the '%s' environment variable to 'true` to enable it", envVarOcsEnabled))
		return nil, nil
	}

	ocsServiceAccountName := os.Getenv(envVarOcsServiceAccountName)
	if ocsServiceAccountName == "" {
		return nil, fmt.Errorf("%s environment variable is required but is empty", envVarOcsServiceAccountName)
	}

	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),
			ocsServiceAccountName:     ocsServiceAccountName,
		}).New,
	}, nil
}

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

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

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