package agentw

import (
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/agentwcfg"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/agent_registrar"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/agent_registrar/agent"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/agent_registrar/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modagentw"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/retry"
)

type Factory struct {
	agent.Factory
}

func (f *Factory) New(config *modagentw.Config) (modagentw.Module, error) {
	m := &agent.Module[*agentwcfg.AgentConfiguration]{
		Log: config.Log,
		PollConfig: retry.NewPollConfigFactory(agent_registrar.RegisterAttemptInterval, retry.NewExponentialBackoffFactory(
			agent.RegisterInitBackoff,
			agent.RegisterMaxBackoff,
			agent.RegisterResetDuration,
			agent.RegisterBackoffFactor,
			agent.RegisterJitter,
		)),
		Client: rpc.NewAgentRegistrarClient(config.KASConn),
		RegisterRequest: func() *rpc.RegisterRequest {
			return &rpc.RegisterRequest{
				Meta: &rpc.RegisterRequest_AgentwMeta{
					AgentwMeta: config.AgentMeta,
				},
				InstanceId: config.InstanceID,
			}
		},
		UnregisterRequest: func() *rpc.UnregisterRequest {
			return &rpc.UnregisterRequest{
				Meta: &rpc.UnregisterRequest_AgentwMeta{
					AgentwMeta: config.AgentMeta,
				},
				InstanceId: config.InstanceID,
			}
		},
	}
	return m, nil
}
