package migration

import (
	"slices"

	"gorm.io/gorm"

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

// Set priority of all spu mapping entries whose tenant whitelist is 0 to 999 (lowest).
var _ = AddDBMigrateRecord(
	"202504011600",
	func(db *gorm.DB) error {
		return db.Transaction(func(tx *gorm.DB) error {
			// list all spu mappings.
			var spuMappings []*schema.TierTierUnit
			if err := tx.Model(&schema.TierTierUnit{}).Find(&spuMappings).Error; err != nil {
				return err
			}

			// list all skus with tenant whitelist 0.
			skuKeys := make([]string, 0)
			// for each spu mapping,
			for _, spuMapping := range spuMappings {
				// for sku item,
				for _, item := range spuMapping.TierUnitMapping.Items {
					if slices.Contains(item.TenantIDs, "0") {
						skuKeys = append(skuKeys, item.SkuKey)
					}
				}
			}

			// set priority to 999 for all sku with key in skuKeys.
			for _, skuKey := range skuKeys {
				if err := tx.Model(&schema.ComponentTierUnit{}).
					Where("`key` = ?", skuKey).
					Update("priority", 999).Error; err != nil {
					return err
				}
			}

			return nil
		})
	},
)
