package server

import (
	"time"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/agent2kas_tunnel"
	"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/tunnel/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) {
	rpc.RegisterReverseTunnelServer(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 agent2kas_tunnel.ModuleName
}
