package migrate

import (
	"github.com/pingcap/log"
	"github.com/tidbcloud/serverless-service/internal/domain/entity"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// 202605240000 initializes the schema for the Essential CDC newarch path.
//
// One migration covers three things; we keep them together so a fresh
// deployment of the newarch feature lands a consistent set of objects:
//
//  1. ALTER `cdc_changefeeds` ADD `arch`, `rcu`
//     Both are inert for the legacy `replication_worker` rows (defaults
//     preserve old behaviour). They only matter for newarch rows.
//  2. CREATE the three newarch-only tables via gorm AutoMigrate so the
//     DDL stays in sync with the entity definitions:
//     - ti_cdc_changefeed_resources  (per-changefeed shard membership)
//     - kernel_ti_cdc_changefeeds    (per-changefeed kernel-side ack)
//     - ticdc_clusters               (per-shard shared TiCDC cluster
//     state, including `version`)
//
// No data backfill — this is the first time the newarch path is
// shipped, so the new tables start empty by construction.
var _ = AddDBMigrateRecord(
	"202605240000",
	func(db *gorm.DB) error {
		alters := []string{
			"ALTER TABLE `cdc_changefeeds` ADD COLUMN `arch` VARCHAR(32) NOT NULL DEFAULT 'replication_worker' AFTER `state`",
			"ALTER TABLE `cdc_changefeeds` ADD COLUMN `rcu` INT UNSIGNED NOT NULL DEFAULT 3 AFTER `arch`",
		}
		for _, sql := range alters {
			if err := db.Exec(sql).Error; err != nil {
				log.Error("alter cdc_changefeeds for newarch failed",
					zap.String("sql", sql), zap.Error(err))
				return err
			}
		}
		if err := db.AutoMigrate(
			&entity.TiCDCChangefeedResource{},
			&entity.KernelTiCDCChangefeed{},
			&entity.TiCDCCluster{},
		); err != nil {
			log.Error("create newarch tables failed", zap.Error(err))
			return err
		}
		return nil
	},
)
