package db

import (
	"time"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

const workflowRunSnapshotMigrationBatchSize = 100

// MigrateWorkflowRunSnapshots moves definition blobs written by earlier
// versions into the one-to-one cold table, then removes the retired column and
// Workflow-catalog-based merge-group identity.
func MigrateWorkflowRunSnapshots(database *gorm.DB) error {
	if database.Migrator().HasColumn("workflow_runs", "workflow_definition") {
		var lastID uint
		for {
			var legacy []struct {
				ID         uint
				Definition LargeText `gorm:"column:workflow_definition"`
				CreatedAt  time.Time
			}
			if err := database.Table("workflow_runs").
				Select("id, workflow_definition, created_at").
				Where("id > ? AND workflow_definition IS NOT NULL AND workflow_definition <> ''", lastID).
				Order("id ASC").Limit(workflowRunSnapshotMigrationBatchSize).
				Find(&legacy).Error; err != nil {
				return err
			}
			for _, row := range legacy {
				snapshot := WorkflowRunSnapshot{
					WorkflowRunID: row.ID,
					Definition:    row.Definition,
					CreatedAt:     row.CreatedAt,
				}
				if err := database.Clauses(clause.OnConflict{DoNothing: true}).Create(&snapshot).Error; err != nil {
					return err
				}
			}
			if len(legacy) < workflowRunSnapshotMigrationBatchSize {
				break
			}
			lastID = legacy[len(legacy)-1].ID
		}
		if err := database.Migrator().DropColumn("workflow_runs", "workflow_definition"); err != nil {
			return err
		}
	}
	if database.Migrator().HasIndex(&WorkflowRun{}, "idx_workflow_merge_group") {
		return database.Migrator().DropIndex(&WorkflowRun{}, "idx_workflow_merge_group")
	}
	return nil
}
