package server

import (
	"context"
	"time"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/agent_tracker"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/agent_tracker/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modserver"
	otelmetric "go.opentelemetry.io/otel/metric"
)

type Factory struct {
	AgentQuerier agent_tracker.Querier
}

func (f *Factory) New(config *modserver.Config) (modserver.Module, error) {
	_, err := config.Meter.Int64ObservableGauge(
		"connected_agents_count",
		otelmetric.WithDescription("The number of unique connected agents"),
		otelmetric.WithInt64Callback(f.connectedAgents),
	)
	if err != nil {
		return nil, err
	}

	rpc.RegisterAgentTrackerServer(config.APIServer, &server{
		agentQuerier:       f.AgentQuerier,
		serverVersion:      config.Version,
		gitlabReleasesList: config.GitLabReleasesList,
	})

	return nil, nil
}

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

func (f *Factory) connectedAgents(ctx context.Context, observer otelmetric.Int64Observer) error {
	ctx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	size, err := f.AgentQuerier.GetConnectedAgentsCount(ctx)
	if err != nil {
		return err
	}
	observer.Observe(size)
	return nil
}
