package metaprofileaction

import (
	"context"
	"encoding/json"
	"fmt"

	ccproto "github.com/tidbcloud/config-center/proto/config_center"
	cloudconfig "github.com/tidbcloud/devops/api/cloudconfig"
	opent "github.com/tidbcloud/devops/entity/operation"
	"github.com/tidbcloud/devops/pkg/service/cloudconfig/cvt"
	"github.com/tidbcloud/devops/pkg/service/operation/actions"
)

var (
	ActionCreateMetaProfile opent.ActionMetadata = opent.ActionMetadata{
		Name: "CreateMetaProfileInConfigCenter",
		Type: opent.ActionTypeAuto,
	}
)

type createMetaProfile struct {
	actions.BaseAction
	comps *actions.Components
}

func NewCreateMetaProfile(comps *actions.Components) actions.AutoAction {
	return &createMetaProfile{
		comps: comps,
	}
}

func (p *createMetaProfile) Metadata() opent.ActionMetadata {
	return ActionCreateMetaProfile
}

func (p *createMetaProfile) PreCheck(ctx context.Context, instance *opent.Instance) error {
	_, err := p.getParam(instance)
	if err != nil {
		return err
	}

	return nil
}

func (p *createMetaProfile) Start(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	req, err := p.getParam(instance)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}
	_, err = p.comps.CloudConfigAPI.CreateMetaProfile(ctx, req)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}
	return actions.SucceededActionResult(nil), nil
}

func (p *createMetaProfile) Result(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	return actions.SucceededActionResult(nil), nil
}

func (p *createMetaProfile) getParam(instance *opent.Instance) (*ccproto.CreateMetaProfileRequest, error) {
	createMetaProfileReq, ok := instance.GetParam(opent.ParamMetaProfifleCreateRequest)
	if !ok {
		return nil, fmt.Errorf(("meta profile create request is not found"))
	}
	req := &cloudconfig.CreateMetaProfileReq{}
	err := json.Unmarshal([]byte(createMetaProfileReq), req)
	if err != nil {
		return nil, fmt.Errorf("unmarshal meta profile create request failed: %v", err)
	}
	return &ccproto.CreateMetaProfileRequest{
		ClusterType:           cvt.To.ConfigCenter.ClusterType(req.ClusterType),
		ProfileName:           req.ProfileName,
		Description:           req.Description,
		ComponentImageTags:    req.ComponentImageTags,
		ConfigCustomTemplates: req.ConfigCustomTemplates,
		ComponentVersions:     req.ComponentVersions,
		Tags: map[string]string{
			ccproto.TEMPLATE_TAG_OWNER_TENANT_ID: req.TenantID,
		},
	}, nil
}
