package server

import (
	"strings"
	"time"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/prototool"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/pkg/agentcfg"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/pkg/kascfg"
)

const (
	defaultKubernetesAPIListenNetwork    = "tcp"
	defaultKubernetesAPIListenAddress    = ":8154"
	defaultListenGracePeriod             = 5 * time.Second
	defaultAllowedAgentInfoCacheTTL      = 1 * time.Minute
	defaultAllowedAgentInfoCacheErrorTTL = 10 * time.Second
	defaultShutdownGracePeriod           = 1 * time.Hour
)

func ApplyDefaults(config *kascfg.ConfigurationFile) {
	prototool.NotNil(&config.Agent)
	prototool.NotNil(&config.Agent.KubernetesApi)
	o := config.Agent.KubernetesApi

	prototool.NotNil(&o.Listen)
	prototool.DefaultValPtr(&o.Listen.Network, defaultKubernetesAPIListenNetwork)
	prototool.DefaultVal(&o.Listen.Address, defaultKubernetesAPIListenAddress)
	prototool.Duration(&o.Listen.ListenGracePeriod, defaultListenGracePeriod)
	prototool.Duration(&o.Listen.ShutdownGracePeriod, defaultShutdownGracePeriod)
	if !strings.HasSuffix(o.UrlPathPrefix, "/") {
		o.UrlPathPrefix += "/"
	}
	prototool.Duration(&o.AllowedAgentCacheTtl, defaultAllowedAgentInfoCacheTTL)
	prototool.Duration(&o.AllowedAgentCacheErrorTtl, defaultAllowedAgentInfoCacheErrorTTL)
}

func ApplyDefaultsToAgentConfig(config *agentcfg.ConfigurationFile) {
	if config.CiAccess != nil {
		for _, g := range config.CiAccess.Groups {
			defaultCIAccessAs(&g.AccessAs)
		}
		for _, p := range config.CiAccess.Projects {
			defaultCIAccessAs(&p.AccessAs)
		}
	}
	if config.UserAccess != nil {
		if config.UserAccess.AccessAs == nil {
			config.UserAccess.AccessAs = &agentcfg.UserAccessAsCF{
				As: &agentcfg.UserAccessAsCF_Agent{},
			}
		}
	}
}

func defaultCIAccessAs(ap **agentcfg.CiAccessAsCF) {
	prototool.NotNil(ap)
	a := *ap
	if a.As == nil {
		a.As = &agentcfg.CiAccessAsCF_Agent{
			Agent: &agentcfg.CiAccessAsAgentCF{},
		}
	}
}
