package server

import (
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modserver"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/runner"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/runner/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/runner_controller"
	"go.opentelemetry.io/otel/metric"
)

const (
	admissionControlTotalCounterName         = "job_router_admission_control_total"
	admissionControlRequestsTotalCounterName = "job_router_admission_control_requests_total"
)

type Factory struct{}

func (f *Factory) New(config *modserver.Config) (modserver.Module, error) {
	admissionControlTotalCounter, err := config.Meter.Int64Counter(
		admissionControlTotalCounterName,
		metric.WithDescription("The total number of times admission control is performed in job router"),
	)
	if err != nil {
		return nil, err
	}
	admissionControlRequestsTotalCounter, err := config.Meter.Int64Counter(
		admissionControlRequestsTotalCounterName,
		metric.WithDescription("The total number of admission control requests performed to individual runner controllers in job router"),
	)
	if err != nil {
		return nil, err
	}

	rpc.RegisterJobRouterServer(config.AgentServer, &server{
		gitlabClient: config.GitLabClient,
		newAdmissionControllerClient: func() admissionControllerClient {
			return runner_controller.NewRunnerControllerClient(config.AgentConnPool)
		},
		admissionControlTotalCounter:         admissionControlTotalCounter,
		admissionControlRequestsTotalCounter: admissionControlRequestsTotalCounter,
	})
	return nil, nil
}

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