package migrate

import (
	"fmt"
	"slices"

	"github.com/tidbcloud/devops/models/approval"
	"github.com/tidbcloud/devops/models/cloudconfig"
	"github.com/tidbcloud/devops/models/release"
	"gorm.io/gorm"
)

// migration for release, cloudconfig and approval service to rename table names.
var _ = AddMigrateRecord(
	"202411041400",
	func(db *gorm.DB) error {
		currentTables := []string{}
		err := db.Raw("SHOW TABLES").Scan(&currentTables).Error
		if err != nil {
			return fmt.Errorf("failed to get current tables: %w", err)
		}

		tables := map[string]string{
			"changes":                             release.Change{}.TableName(),
			"change_details":                      release.ChangeDetail{}.TableName(),
			"change_notifications":                release.ChangeNotification{}.TableName(),
			"change_deployments":                  release.ChangeDeployment{}.TableName(),
			"releases":                            release.Release{}.TableName(),
			"configuration_change_to_tenant_init": cloudconfig.ConfigurationChangeToTenantInit{}.TableName(),
			"configuration_change_to_cluster":     cloudconfig.ConfigurationChangeToCluster{}.TableName(),
			"configuration_file_changes":          cloudconfig.ConfigurationFileChange{}.TableName(),
			"configuration_version_changes":       cloudconfig.ConfigurationVersionChange{}.TableName(),
			"configuration_component_changes":     cloudconfig.ConfigurationComponentChange{}.TableName(),
			"configuration_changes":               cloudconfig.ConfigurationChange{}.TableName(),
			"approvals_v2":                        approval.Approval{}.TableName(),
		}

		for from, to := range tables {
			if slices.Contains(currentTables, to) {
				continue
			}

			err := db.Exec(fmt.Sprintf(`RENAME TABLE %s TO %s`, from, to)).Error
			if err != nil {
				return fmt.Errorf("rename %s to %s failed: %v", from, to, err)
			}
		}
		return nil

	},
)
