package migration

import (
	"github.com/samber/lo"
	"gorm.io/gorm"

	"github.com/tidbcloud/tidb-management-service/dedicated-global-service/infra/repoimpl/schema"
)

// old schema
type ClusterComponent struct {
	gorm.Model

	WorkPoolId           uint64  `gorm:"index:comp_group,unique"`
	ComponentType        string  `gorm:"index:comp_group,unique"`
	ClusterId            uint64  `gorm:"index:comp_group,unique"`
	ComponentTierKey     string  `gorm:"index"`
	ComponentTierUnitKey string  `gorm:"index"`
	VolumeType           *string // will be deprecated
	Iops                 *uint32 // will be deprecated
	StorageSizeGi        *uint32 // will be deprecated
	ThroughPutMibps      *uint32 // will be deprecated
	Count                uint32
}

var _ = AddDBMigrateRecord(
	"202407181010",
	func(db *gorm.DB) error {
		if err := db.AutoMigrate(&schema.ClusterComponentStorage{}); err != nil {
			return err
		}

		// migrate cluster_components
		var clusterComps []*ClusterComponent
		err := db.Unscoped().Model(&ClusterComponent{}).Where("component_type != 'tidb'").Find(&clusterComps).Error
		if err != nil {
			return err
		}

		for _, clusterComp := range clusterComps {
			clusterCompStorage := &schema.ClusterComponentStorage{
				Model: gorm.Model{
					ID:        0, // auto increment
					CreatedAt: clusterComp.CreatedAt,
					UpdatedAt: clusterComp.UpdatedAt,
					DeletedAt: clusterComp.DeletedAt,
				},
				ClusterComponentId: uint64(clusterComp.ID),
				StorageType:        "data", // default value
				VolumeType:         clusterComp.VolumeType,
				SizeGi:             lo.FromPtr(clusterComp.StorageSizeGi),
				Iops:               clusterComp.Iops,
				ThroughPutMibps:    clusterComp.ThroughPutMibps,
			}

			if err := db.Create(clusterCompStorage).Error; err != nil {
				return err
			}
		}

		// drop columns
		if err := db.Exec(
			"ALTER TABLE `cluster_components` drop column `volume_type`,drop column `iops`,drop column `storage_size_gi`,drop column `through_put_mibps`;",
		).Error; err != nil {
			return err
		}
		return nil
	},
)
