package agentk

import (
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/kubernetes_api"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/kubernetes_api/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modagentk"
	"k8s.io/client-go/rest"
)

type Factory struct {
}

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

func (f *Factory) New(config *modagentk.Config) (modagentk.Module, error) {
	restConfig, err := config.K8sUtilFactory.ToRESTConfig()
	if err != nil {
		return nil, err
	}

	restConfig = rest.CopyConfig(restConfig)
	// Clients and the server already do rate limiting. agentk doesn't need to add an extra layer.
	// See https://kubernetes.io/docs/concepts/cluster-administration/flow-control/
	restConfig.QPS = -1
	restConfig.UserAgent = config.AgentNameVersion
	baseURL, _, err := rest.DefaultServerUrlFor(restConfig)
	if err != nil {
		return nil, err
	}

	s, err := newServer(config.Validator, restConfig, config.K8sUtilFactory.NewBuilder, baseURL, config.AgentNameVersion, config.AgentMeta.Version)
	if err != nil {
		return nil, err
	}
	rpc.RegisterKubernetesApiServer(config.APIServer, s)
	return nil, nil
}

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