package migrate_record

import (
	"github.com/pingcap/dbaas/billing2/db/entity"
	"gorm.io/gorm"
)

// 2026-08-21-merged-labels-history
//
// Adds the merged_labels_history JSON column so merged rows can preserve
// per-raw-cost label history across merges and let MSP/CPPO SecondaryMeasure
// replay each contribution with its original labels.
//
// AutoMigrate brings the column to BOTH tables that carry the field: the
// explicit user_unit_costs entity and raw_user_unit_costs (RawUserUnitCost
// embeds UserUnitCost). The raw table MUST get the column on warm DBs —
// txCost updates the raw row with Select("*"), which emits
// merged_labels_history in the SET clause and fails with MySQL error 1054
// if the column is missing. InitSchema (which would AutoMigrate) never runs
// on warm DBs, so the AutoMigrate call here is what patches warm prod, same
// as migrate_record170/171.
//
// Idempotency: the ALTER below is guarded by an information_schema.columns
// lookup so the migration is safe to re-run on partially-migrated DBs and
// on warm DBs where the column already exists (e.g. created by an earlier
// deployment's AutoMigrate).
var _ = AddMigrateRecord(
	"2026-08-21-merged-labels-history",
	func(db *gorm.DB) error {
		// AutoMigrate picks up the entity tag change for fresh DBs and
		// brings warm DBs up to the entity definition on both tables.
		if err := db.AutoMigrate(entity.Models...); err != nil {
			return err
		}

		// Belt-and-braces for user_unit_costs: if AutoMigrate did not add
		// the column (e.g. a deployment where the entity list drifted),
		// add it explicitly.
		var colCount int
		if err := db.Raw(
			"SELECT COUNT(*) FROM information_schema.columns "+
				"WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",
			"user_unit_costs", "merged_labels_history",
		).Scan(&colCount).Error; err != nil {
			return err
		}
		if colCount > 0 {
			return nil
		}
		return db.Exec(
			"ALTER TABLE user_unit_costs ADD COLUMN merged_labels_history JSON NULL",
		).Error
	},
)
