// Filename: internal/db/migrations/versioned_migrations.go

package migrations

import (
	"fmt"
	"gemini-balancer/internal/config"

	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

// RunVersionedMigrations 负责运行所有已注册的版本化迁移。
func RunVersionedMigrations(db *gorm.DB, cfg *config.Config, logger *logrus.Logger) error {
	log := logger.WithField("component", "versioned_migrations")
	log.Info("Checking for versioned database migrations...")

	if err := db.AutoMigrate(&MigrationHistory{}); err != nil {
		log.Errorf("Failed to create migration history table: %v", err)
		return err
	}

	var executedMigrations []MigrationHistory
	db.Find(&executedMigrations)
	executedVersions := make(map[string]bool)
	for _, m := range executedMigrations {
		executedVersions[m.Version] = true
	}

	for _, migration := range migrationRegistry {
		if !executedVersions[migration.Version] {
			log.Infof("Running migration %s: %s", migration.Version, migration.Description)
			if err := migration.Migrate(db, cfg, log); err != nil {
				log.Errorf("Migration %s failed: %v", migration.Version, err)
				return fmt.Errorf("migration %s failed: %w", migration.Version, err)
			}
			db.Create(&MigrationHistory{Version: migration.Version})
			log.Infof("Migration %s completed successfully.", migration.Version)
		}
	}

	log.Info("All versioned migrations are up to date.")
	return nil
}

type MigrationFunc func(db *gorm.DB, cfg *config.Config, logger *logrus.Entry) error
type VersionedMigration struct {
	Version     string
	Description string
	Migrate     MigrationFunc
}
type MigrationHistory struct {
	Version string `gorm:"primaryKey"`
}

var migrationRegistry = []VersionedMigration{
	/*{
		Version:     "20250828_encrypt_existing_auth_tokens",
		Description: "Encrypt plaintext tokens and populate new crypto columns in auth_tokens table.",
		Migrate:     MigrateAuthTokenEncryption,
	},*/
}
