package agentw

import (
	"context"

	"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/agentw_rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modagentw"
	"gitlab.com/gitlab-org/cluster-integration/tunnel/tool/retry"
)

type Factory struct {
	agent.Factory
}

func (f *Factory) New(config *modagentw.Config) (modagentw.Module, error) {
	client := agentw_rpc.NewAgentRegistrarClient(config.KASConn)

	m := &agent.Module[*agentwcfg.AgentConfiguration]{
		Log: config.Log,
		PollConfig: retry.PollConfig{
			Interval: agent_registrar.RegisterAttemptInterval,
			Backoff: retry.NewExponentialBackoff(
				agent.RegisterInitBackoff,
				agent.RegisterMaxBackoff,
				agent.RegisterResetDuration,
				agent.RegisterBackoffFactor,
				agent.RegisterJitter,
			),
		},
		Register: func(ctx context.Context) error {
			_, err := client.Register(ctx, &agentw_rpc.RegisterRequest{
				Meta:       config.AgentMeta,
				InstanceId: config.InstanceID,
			})
			return err
		},
		Unregister: func(ctx context.Context) error {
			_, err := client.Unregister(ctx, &agentw_rpc.UnregisterRequest{
				Meta:       config.AgentMeta,
				InstanceId: config.InstanceID,
			})
			return err
		},
	}
	return m, nil
}
