package task

import (
	"context"

	"github.com/tidbcloud/eks-provider/pkg/config"
	"github.com/tidbcloud/eks-provider/pkg/deploy"
	"github.com/tidbcloud/eks-provider/pkg/helm"

	"helm.sh/helm/v3/pkg/chart"
	"helm.sh/helm/v3/pkg/chart/loader"

	apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
)

type Proxy struct {
	*BaseTask
	config *ProxyConfig
}

type ProxyConfig struct {
	helmChartPath string

	proxyImage config.ImageConfig
	gottyImage config.ImageConfig
}

func (c *ProxyConfig) GetNamespace() string {
	return adminNamespace
}

func (c *ProxyConfig) GetName() string {
	return "proxy"
}

func (c *ProxyConfig) ToHelmChart() (result *chart.Chart, err error) {
	return loader.Load(c.helmChartPath)
}

func (c *ProxyConfig) ToHelmValues() map[string]interface{} {
	return map[string]interface{}{
		"replicaCount": 2,
		"image": map[string]string{
			"repository": c.proxyImage.Repo,
			"tag":        c.proxyImage.Tag,
		},
		"gotty": map[string]string{
			"repository": c.gottyImage.Repo,
			"tag":        c.gottyImage.Tag,
		},
	}
}

func (c *ProxyConfig) GetCRDs() ([]*apiextensionsv1.CustomResourceDefinition, error) {
	return nil, nil
}

func NewProxy(ctx *Context) *Proxy {
	return &Proxy{
		BaseTask: &BaseTask{Context: ctx},
		config: &ProxyConfig{
			helmChartPath: ctx.Config.Network.Proxy.ChartPath,
			proxyImage:    ctx.Config.Network.Proxy.ProxyImage,
			gottyImage:    ctx.Config.Network.Proxy.GottyImage,
		},
	}
}

func (t *Proxy) Name() string {
	return "Proxy"
}

func (t *Proxy) Create(ctx context.Context) deploy.Result {
	if t.remote == nil {
		return deploy.Skip("empty remote client")
	}
	return deploy.FromError(helm.Apply(ctx, t.remote, t.config))
}

func (t *Proxy) PostCreate(ctx context.Context) deploy.Result {
	// TODO(tangent): Update network status
	return deploy.FromError(nil)
}
