package component

import (
	"context"

	eksv1alpha1 "github.com/tidbcloud/eks-provider/api/v1alpha1"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/config"
	"github.com/tidbcloud/eks-provider/controllers/tiflow/task/cluster/executor"
	"github.com/tidbcloud/infra-provider/pkg/gitops-sdk/utils"
)

func NewExecutorConfigQuirer(ctx *executor.Context) config.ClusterConfigQuirer {
	return &ExecutorConfigQuirer{
		Context: ctx,
	}
}

type ExecutorConfigQuirer struct {
	*executor.Context
}

func (t *ExecutorConfigQuirer) Execute(ctx context.Context) (*config.ClusterConfig, error) {
	baseQuirer := config.ConfigQuirerFactory(t.Config, false /*IsMaster*/)
	cc, err := baseQuirer.Execute(ctx)
	if err != nil {
		return nil, err
	}

	if err := t.overlayConfig(ctx, cc); err != nil {
		return nil, err
	}

	return cc, nil
}

func (t *ExecutorConfigQuirer) overlayConfig(ctx context.Context, cc *config.ClusterConfig) error {
	executorConfig := &config.TiflowClusterExecutorConfig{
		Labels: map[string]string{
			eksv1alpha1.TiflowJobToEngineSelectorLabelKey: t.Namer.GetTiflowClusterName(),
		},
	}

	tiflowExecutorConfig, err := config.ConvertTiflowExecutorConfig(executorConfig)
	if err != nil {
		return err
	}

	if cc.Config == nil {
		cc.Config = tiflowExecutorConfig
		return nil
	}

	// NOTE: local config will overlay gitops config
	cc.Config = utils.MergeMaps(cc.Config, tiflowExecutorConfig)
	return nil
}
