package action

import (
	"fmt"

	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	"github.com/tidbcloud/cluster-service-ng/pkg/clusterconfig"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	"github.com/tidbcloud/cluster-service-ng/pkg/storage/repo"
	"github.com/tidbcloud/cluster-service-ng/pkg/utils"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"google.golang.org/protobuf/encoding/protojson"
)

type CreateComponentConfigAction struct {
	sharedPoolRepo      repo.SharedPoolRepo
	clusterConfigClient clusterconfig.Client
}

const CreateComponentConfigName = "create-component-config"

func NewCreateComponentConfigAction(
	sharedPoolRepo repo.SharedPoolRepo,
	clusterConfigClient clusterconfig.Client,
) actions.Action {
	return &CreateComponentConfigAction{
		sharedPoolRepo:      sharedPoolRepo,
		clusterConfigClient: clusterConfigClient,
	}
}

func (a *CreateComponentConfigAction) Name() string {
	return CreateComponentConfigName
}

// Invoke creates component config in config center
func (a *CreateComponentConfigAction) Invoke(args actions.ActionArgs) error {
	// generate context
	ctx := utils.GenerateContext(args)
	tilog.Info(ctx, "create component config action invoked")

	sharedPoolId, err := args.GetString(workflow.SharedPoolIdKey)
	if err != nil {
		return fmt.Errorf("failed to get sharedPool id: %w", err)
	}

	// load sharedPool
	sharedPool, err := a.sharedPoolRepo.Load(ctx, sharedPoolId, false)
	if err != nil {
		return fmt.Errorf("failed to load sharedPool: %w", err)
	}

	sharedPoolStr, err := args.GetString(workflow.SharedPoolKey)
	if err != nil {
		return fmt.Errorf("failed to get sharedPool: %w", err)
	}

	var tempSharedPool entity.SharedPool
	err = protojson.Unmarshal([]byte(sharedPoolStr), &tempSharedPool)
	if err != nil {
		tilog.Error(ctx, "failed to unmarshal sharedPool", zap.Error(err))
		return fmt.Errorf("failed to unmarshal sharedPool: %w", err)
	}
	sharedPool.ComponentGroups = tempSharedPool.GetComponentGroups()

	// Find target components using CheckIsTargetComponent
	for _, comp := range sharedPool.GetComponentGroups() {
		if !workflow.CheckIsTargetComponent(ctx, comp, args) {
			continue
		}

		err = a.clusterConfigClient.CreateNewComponentConfig(ctx, sharedPool, comp)
		if err != nil {
			tilog.Error(ctx, "failed to create component config",
				zap.String("componentId", comp.GetId()),
				zap.String("componentType", entity.GetComponentTypeName(comp)),
				zap.Error(err))
			return fmt.Errorf("failed to create component config for %s: %w", comp.GetId(), err)
		}

		tilog.Info(ctx, "create component config completed",
			zap.String("componentId", comp.GetId()),
			zap.String("componentType", entity.GetComponentTypeName(comp)))
	}

	return nil
}
