package eks

import (
	"context"
	"fmt"

	"helm.sh/helm/v3/pkg/chart"
	"helm.sh/helm/v3/pkg/chart/loader"
	apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"

	"github.com/tidbcloud/eks-provider/controllers/network/task"
	"github.com/tidbcloud/infra-provider/pkg/config"
	"github.com/tidbcloud/infra-provider/pkg/deploy"
	"github.com/tidbcloud/infra-provider/pkg/helm"
)

type Reporter struct {
	*task.BaseTask
	config *SLIReporterConfig
}

type SLIReporterConfig struct {
	helmChartPath string
	image         config.ImageConfig

	awsRegion                string
	awsDeliveryStreamName    string
	awsDeliveryStreamRoleArn string
}

func (c *SLIReporterConfig) GetNamespace() string {
	return task.AdminNamespace
}

func (c *SLIReporterConfig) GetName() string {
	return "reporter"
}

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

func (c *SLIReporterConfig) ToHelmChart() (result *chart.Chart, err error) {
	result, err = loader.Load(c.helmChartPath)
	if err != nil {
		return nil, fmt.Errorf("failed to load helm chart %q: %w", c.helmChartPath, err)
	}
	return
}

func (c *SLIReporterConfig) ToHelmValues() map[string]interface{} {
	return map[string]interface{}{
		"replicaCount": 1,
		"image": map[string]string{
			"repository": c.image.Repo,
			"tag":        c.image.Tag,
		},
		"aws": map[string]string{
			"region":                c.awsRegion,
			"deliveryStreamName":    c.awsDeliveryStreamName,
			"deliveryStreamRoleArn": c.awsDeliveryStreamRoleArn,
		},
	}
}

func NewReporter(ctx *task.Context) *Reporter {
	return &Reporter{
		BaseTask: &task.BaseTask{Context: ctx},
		config: &SLIReporterConfig{
			helmChartPath:            ctx.Config.Network.SLIReporter.ChartPath,
			image:                    ctx.Config.Network.SLIReporter.Image,
			awsRegion:                ctx.Config.Network.SLIReporter.AWSRegion,
			awsDeliveryStreamName:    ctx.Config.Network.SLIReporter.DeliveryStreamName,
			awsDeliveryStreamRoleArn: ctx.Config.Network.SLIReporter.DeliveryStreamRoleArn,
		},
	}
}

var _ helm.Package = &SLIReporterConfig{}

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

func (t *Reporter) Create(ctx context.Context) deploy.Result {
	return deploy.ErrorOrDone(helm.Apply(ctx, t.Remote, t.config))
}

func (t *Reporter) PostCreate(ctx context.Context) deploy.Result {
	return deploy.Done()
}

func (t *Reporter) Delete(ctx context.Context) deploy.Result {
	return deploy.Done()
}

func (t *Reporter) PostDelete(ctx context.Context) deploy.Result {
	return deploy.Done()
}
