package db

import (
	"time"

	"github.com/tidbcloud/cluster-service-ng/pkg/storage/mysql/schema"
	"gorm.io/gorm"
)

type tidbGroup struct {
	ID              string `gorm:"type:varchar(128);primarykey"` // unique TidbGroup id
	SharedPoolID    string `gorm:"type:varchar(128);index"`
	ClusterID       string `gorm:"type:varchar(128);index"`
	TenantID        string `gorm:"type:varchar(128);index"`
	KeySpace        string `gorm:"type:varchar(128);not null;index"`
	RUMin           int64  `gorm:"not null"`
	RUMax           int64  `gorm:"not null"`
	DataplaneName   string `gorm:"not null"`
	TemplateVersion int64  `gorm:"index"` // version of the template used to create this shared pool
	CreatedAt       time.Time
	UpdatedAt       time.Time
	DeletedAt       gorm.DeletedAt `gorm:"index"`
}

var _ = AddDBMigrateRecord(
	"20250909001",
	func(db *gorm.DB) error {

		return db.Transaction(func(tx *gorm.DB) error {

			if err := tx.AutoMigrate(&schema.TidbCluster{}); err != nil {
				return err
			}

			var tidbGroups []*tidbGroup
			// list all not deleted tidb groups
			if err := tx.Where("deleted_at IS NULL").Find(&tidbGroups).Error; err != nil {
				return err
			}

			// for each tidb group, create a tidb cluster record
			// use a map to avoid duplicate cluster records
			clusterMap := make(map[string]*schema.TidbCluster)
			for _, group := range tidbGroups {
				// Skip if ClusterID is empty
				if group.ClusterID == "" {
					continue
				}
				// Only create one TidbCluster record per unique ClusterID
				if _, exists := clusterMap[group.ClusterID]; !exists {
					clusterMap[group.ClusterID] = &schema.TidbCluster{
						ID:              group.ClusterID,
						TenantID:        group.TenantID,
						SharedPoolID:    group.SharedPoolID,
						RUMin:           group.RUMin,
						RUMax:           group.RUMax,
						TemplateVersion: group.TemplateVersion,
						CreatedAt:       group.CreatedAt,
						UpdatedAt:       group.UpdatedAt,
					}
				}
			}

			// Save all unique clusters
			for _, cluster := range clusterMap {
				if err := tx.Save(cluster).Error; err != nil {
					return err
				}
			}

			// drop the old columns from tidb_groups table
			if err := tx.Exec("ALTER TABLE tidb_groups DROP COLUMN key_space").Error; err != nil {
				return err
			}
			if err := tx.Exec("ALTER TABLE tidb_groups DROP COLUMN ru_min").Error; err != nil {
				return err
			}
			if err := tx.Exec("ALTER TABLE tidb_groups DROP COLUMN ru_max").Error; err != nil {
				return err
			}
			return nil
		})
	},
)
