package db

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

var _ = AddDBMigrateRecord(
	"202602270001",
	func(db *gorm.DB) error {
		migrator := db.Migrator()

		// NOTE:
		// This migration is intentionally destructive for node instance group related tables.
		// It is introduced during a schema reset phase where these tables are confirmed
		// to be non-production / non-critical and can be rebuilt from scratch.
		// Do not reuse this pattern for normal online schema evolution.

		// Drop legacy tables from previous implementations.
		legacyTables := []string{
			"nodegroup_fallback_configs",
			"nodegroups",
			"nodegroup_states",
			"nodegroup_locks",
		}
		for _, table := range legacyTables {
			if migrator.HasTable(table) {
				if err := migrator.DropTable(table); err != nil {
					return err
				}
			}
		}

		// Drop and recreate node_instance_group tables to ensure clean state.
		// This handles the case where dev environment has old schema with deprecated columns.
		// Includes both old names (without dataplane_ prefix) and new names.
		tablesToDrop := []string{
			"node_instance_groups",
			"node_instance_group_states",           // old name (without dataplane_ prefix)
			"node_instance_group_locks",            // old name (without dataplane_ prefix)
			"dataplane_node_instance_group_states", // new name
			"dataplane_node_instance_group_locks",  // new name
			"dataplane_node_instance_groups",
		}
		for _, table := range tablesToDrop {
			if migrator.HasTable(table) {
				if err := migrator.DropTable(table); err != nil {
					return err
				}
			}
		}

		// Create tables with current schema.
		return db.AutoMigrate(
			&schema.NodeInstanceGroup{},
			&schema.DataplaneNodeInstanceGroupState{},
			&schema.DataplaneNodeInstanceGroupLock{},
			&schema.DataplaneNodeInstanceGroup{},
		)
	},
)
