package agent

import (
	"context"

	"github.com/robfig/cron/v3"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modagent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/syncz"
	"go.uber.org/zap"
	"k8s.io/client-go/kubernetes"
)

type workerFactory struct {
	log                       *zap.Logger
	api                       modagent.Api
	kubeClientset             kubernetes.Interface
	gitlabAgentNamespace      string
	gitlabAgentServiceAccount string
}

func (f *workerFactory) New(cfg configurationToUpdateData) syncz.Worker {
	config := cfg.containerScanningConfig
	if config == nil {
		return syncz.WorkerFunc(func(ctx context.Context) {}) // do nothing
	}

	cadence, _ := cron.ParseStandard(config.Cadence)

	var targetNamespaces []string
	if config.VulnerabilityReport != nil {
		targetNamespaces = config.VulnerabilityReport.Namespaces
	}

	return &schedulerWorker{
		job: &scanJob{
			log:                       f.log,
			api:                       f.api,
			kubeClientset:             f.kubeClientset,
			gitlabAgentNamespace:      f.gitlabAgentNamespace,
			gitlabAgentServiceAccount: f.gitlabAgentServiceAccount,
			agentID:                   cfg.agentId,
			targetNamespaces:          targetNamespaces,
			logParser:                 &logParserImpl{},
			resourceRequirements:      config.ResourceRequirements,
		},
		cadence: cadence,
	}
}
