package migrate

import (
	"context"

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

// fix `on_new_arch`
var _ = AddCoreMigrateRecord(
	"202212081727",
	func(db *gorm.DB) error {
		logger := log.WithContextS(context.Background())
		return db.Transaction(func(tx *gorm.DB) error {
			logger.Infof("start migrate on_new_arch")

			statuses := []model.ClusterStatus{
				model.ClusterStatusInitializing,
				model.ClusterStatusPreparing,
				model.ClusterStatusLaunching,
				model.ClusterStatusScaling,
				model.ClusterStatusRecovering,
				model.ClusterStatusNormal,
				model.ClusterStatusPausing,
				model.ClusterStatusPaused,
				model.ClusterStatusResuming,
				model.ClusterStatusDeleted,
				model.ClusterStatusDeletecomplete,
			}
			// load
			var clusters []*model.Cluster
			if err := db.Model(&model.Cluster{}).
				Preload("Provider").Preload("ComponentsV2.Region").
				Where("status in (?)", statuses).Where("free = ?", false).
				Find(&clusters).Error; err != nil {
				return err
			}

			// migrate
			for _, cluster := range clusters {
				region := ""
				for _, each := range cluster.ComponentsV2 {
					if each.Region != nil {
						region = each.Region.Name
						break
					}
				}
				onNewArch := feature_gate.OnNewArch(cluster.TenantID.Uint64(), cluster.ProjectID.Uint64(), string(cluster.Provider.Name), region)
				if onNewArch {
					if !cluster.OnNewArch { // update from `false` to `true`
						cluster.OnNewArch = onNewArch
						logger.Infof("cluster %d is on new arch", cluster.ID)
						if err := cluster.Update(tx, model.ClusterDBSchema.OnNewArch); err != nil {
							return err
						}
					}
				} else {
					if cluster.OnNewArch { // revert from `true` to `false`
						cluster.OnNewArch = false
						logger.Warnf("revert cluster %d on_new_arch to false", cluster.ID)
						if err := cluster.Update(tx, model.ClusterDBSchema.OnNewArch); err != nil {
							return err
						}
					}
				}
			}

			logger.Infof("finish migrate on_new_arch")
			return nil
		})
	},
)
