package migration

import (
	"gorm.io/gorm"

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

type tidbGroup struct {
	gorm.Model

	DisplayName string `gorm:"type:VARCHAR(255);not null"`
	Default     bool   `gorm:"not null"`
	ClusterId   uint64 `gorm:"index"`
	MinRcu      int64  `gorm:"default:0"` // remove to cluster
	MaxRcu      int64  `gorm:"default:0"` // remove to cluster
}

// Migration 202509090001: Move min_rcu and max_rcu from tidb_groups table to cluster table
// This migration is safe to run multiple times as:
// 1. AutoMigrate is idempotent
// 2. UPDATE operations on non-existent cluster IDs will not fail
// 3. DROP COLUMN operations on non-existent columns will fail, but that's handled by the transaction
var _ = AddDBMigrateRecord(
	"202509090001",
	func(db *gorm.DB) error {
		return db.Transaction(func(tx *gorm.DB) error {
			// add new columns to cluster table
			if err := tx.AutoMigrate(&schema.Cluster{}); err != nil {
				return err
			}

			// select tidb groups
			var tidbGroups []tidbGroup
			if err := tx.Find(&tidbGroups).Error; err != nil {
				return err
			}

			// migrate min/max rcu to cluster table
			for _, tg := range tidbGroups {
				if err := tx.Exec("UPDATE clusters SET min_rcu = ?, max_rcu = ? WHERE id = ?", tg.MinRcu, tg.MaxRcu, tg.ClusterId).Error; err != nil {
					return err
				}
			}

			// drop min_rcu and max_rcu from tidb group table
			if err := tx.Exec("ALTER TABLE tidb_groups DROP COLUMN min_rcu").Error; err != nil {
				return err
			}
			if err := tx.Exec("ALTER TABLE tidb_groups DROP COLUMN max_rcu").Error; err != nil {
				return err
			}

			return nil
		})
	},
)
