package migrate

import (
	"context"
	"fmt"
	"strings"

	"github.com/tidbcloud/core-svc/model"
	"github.com/tidbcloud/pkgv2/log"
	"gorm.io/gorm"
)

// migration for add displayName for old nodeProfile
var _ = AddCoreMigrateRecord(
	"202207041832",
	func(db *gorm.DB) error {
		logger := log.WithContextS(context.Background())
		return db.Transaction(func(tx *gorm.DB) error {
			logger.Infof("start migrate LabelProfileDisplayName")

			// load
			var labelProfiles []*model.LabelProfile
			if err := db.Model(&model.LabelProfile{}).
				Preload("InternalProfile").Preload("InternalProfile.InfraCompute").
				Find(&labelProfiles).Error; err != nil {
				return err
			}

			// migrate
			for _, labelProfile := range labelProfiles {
				labelProfile.DisplayName = getLabelProfileDisplayName(labelProfile)
				logger.Infof("labelProfile=%+v", labelProfile)
			}

			// update
			for _, each := range labelProfiles {
				if err := each.Update(db, model.LabelProfileDBSchema.DisplayName); err != nil {
					return err
				}
			}
			logger.Infof("end migrate LabelProfileDisplayName")
			return nil
		})
	},
)

// origin: "2 vCPU (Beta)", target: "2 vCPU, 8 GiB (Beta)"
func getLabelProfileDisplayName(labelProfile *model.LabelProfile) string {
	if labelProfile.DisplayName != "" {
		return labelProfile.DisplayName
	}

	// compatible for "16 vCPU 64 GiB", changed by command line
	if strings.Contains(labelProfile.Name, "GiB") {
		return labelProfile.DisplayName
	}

	// such as: 'aws_freetier_10' for devtier, 'c5.xlarge/gp2' for pd
	if !strings.Contains(labelProfile.Name, "vCPU") {
		return labelProfile.Name
	}

	substrList := strings.SplitN(labelProfile.Name, " vCPU", 2)
	result := fmt.Sprintf("%s vCPU, %d GiB%s", substrList[0], labelProfile.InternalProfile.InfraCompute.MemorySizeGi, substrList[1])
	return result
}
