package server

import (
	"time"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/agent2kas_tunnel/router"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modserver"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/runner_controller"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/runner_controller/rpc"
	"gitlab.com/gitlab-org/cluster-integration/tunnel/tool/retry"
)

const (
	getAgentInfoInitBackoff   = 20 * time.Millisecond
	getAgentInfoMaxBackoff    = 5 * time.Minute
	getAgentInfoResetDuration = 10 * time.Minute
	getAgentInfoBackoffFactor = 2.0
	getAgentInfoJitter        = 5.0
)

type Factory struct {
	TunnelHandler router.Handler
}

func (f *Factory) New(config *modserver.Config) (modserver.Module, error) {
	// Register RPC service for Gateways.
	config.RegisterAgentAPI(&rpc.RunnerControllerService_ServiceDesc)

	// Register the server-side RPC handler
	// This handles incoming AdmitJob calls from agents (agents are the RPC clients)
	rpc.RegisterRunnerControllerServiceServer(config.AgentServer, &server{
		tunnelHandler: f.TunnelHandler,
		getAgentInfoPollConfig: retry.PollConfig{
			Interval: 0,
			Backoff: retry.NewExponentialBackoff(
				getAgentInfoInitBackoff,
				getAgentInfoMaxBackoff,
				getAgentInfoResetDuration,
				getAgentInfoBackoffFactor,
				getAgentInfoJitter,
			),
		},
	})

	return nil, nil
}

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