package server

import (
	"encoding/base64"
	"time"

	gapi "gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/gitlab/api"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/flux"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/flux/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modserver"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modshared"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/server_api"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/cache"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/prototool"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/redistool"
	"gitlab.com/gitlab-org/cluster-integration/tunnel/tool/retry"
	otelmetric "go.opentelemetry.io/otel/metric"
)

const (
	reconcileProjectsInitBackoff   = 10 * time.Second
	reconcileProjectsMaxBackoff    = 5 * time.Minute
	reconcileProjectsResetDuration = 10 * time.Minute
	reconcileProjectsBackoffFactor = 2.0
	reconcileProjectsJitter        = 5.0
	projectAccessCacheTTL          = 5 * time.Minute
	projectAccessCacheErrTTL       = 1 * time.Minute

	fluxNotifiedCounterMetricName             = "flux_git_push_notifications"
	fluxDroppedNotificationsCounterMetricName = "flux_dropped_git_push_notifications"
	fluxNotifiedProjectsCounterMetricName     = "flux_git_push_notified_unique_projects"
)

type Factory struct {
}

func (f *Factory) New(config *modserver.Config) (modserver.Module, error) {
	promNotifiedCounter, err := config.Meter.Int64Counter(
		fluxNotifiedCounterMetricName,
		otelmetric.WithDescription("The total number of sent git push notifications to agentks in Flux module"),
	)
	if err != nil {
		return nil, err
	}
	promDroppedCounter, err := config.Meter.Int64Counter(
		fluxDroppedNotificationsCounterMetricName,
		otelmetric.WithDescription("The total number of dropped git push notifications in Flux module"),
	)
	if err != nil {
		return nil, err
	}
	rpc.RegisterGitLabFluxServer(config.AgentServer, &server{
		serverAPI:               config.API,
		notifiedCounter:         promNotifiedCounter,
		notifiedUsageCounter:    config.UsageTracker.RegisterCounter(fluxNotifiedCounterMetricName),
		notifiedProjectsCounter: config.UsageTracker.RegisterUniqueCounter(fluxNotifiedProjectsCounterMetricName),
		droppedCounter:          promDroppedCounter,
		pollConfig: retry.PollConfig{
			Interval: 0,
			Backoff: retry.NewExponentialBackoff(
				reconcileProjectsInitBackoff,
				reconcileProjectsMaxBackoff,
				reconcileProjectsResetDuration,
				reconcileProjectsBackoffFactor,
				reconcileProjectsJitter,
			),
		},
		projectAccessClient: &projectAccessClient{
			gitLabClient: config.GitLabClient,
			projectAccessCache: cache.NewWithError[projectAccessCacheKey, bool](
				projectAccessCacheTTL,
				projectAccessCacheErrTTL,
				&redistool.ErrCacher[projectAccessCacheKey]{
					Log:          config.Log,
					ErrRep:       modshared.APIToErrReporter(config.API),
					Client:       config.RedisClient,
					ErrMarshaler: prototool.ProtoErrMarshaler{},
					KeyToRedisKey: func(cacheKey projectAccessCacheKey) string {
						return config.Config.Redis.KeyPrefix +
							":verify_project_access_errs:" +
							base64.StdEncoding.EncodeToString(server_api.AgentToken2key(cacheKey.agentToken)) +
							":" +
							cacheKey.projectID
					},
				},
				config.TraceProvider.Tracer(flux.ModuleName),
				gapi.IsCacheableError,
			),
		},
	})
	return nil, nil
}

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