package command

import (
	migrator "git.gocasts.ir/ebhomengo/niki/pkg/database/migrator"
	"git.gocasts.ir/ebhomengo/niki/pkg/logger"
	"github.com/spf13/cobra"
)

var up bool
var down bool

var migrateCmd = &cobra.Command{
	Use:   "migrate",
	Short: "Run database migrations",
	Long:  `This command runs the database migrations for the benefactor service.`,
	Run: func(cmd *cobra.Command, args []string) {
		migrate()
	},
}

func migrate() {
	var cfg = loadAppConfig()
	mysqlConfig := getMysqlConfig()

	logger.Init(cfg.Logger)
	log := logger.L()

	migratorCfg := migrator.Config{
		MysqlConfig:     mysqlConfig,
		MigrationPath:   cfg.PathOfMigration,
		MigrationDBName: "gorp_migrations",
	}
	// Run migrations if flags are set
	if migrateUp || migrateDown {
		mgr := migrator.New(migratorCfg)
		if migrateUp {
			log.Info("Running migrations up...")
			mgr.Up()
			log.Info("Migrations up completed.")
		}
		if migrateDown {
			log.Info("Running migrations down...")
			mgr.Down()
			log.Info("Migrations down completed.")
		}
	}
}

func init() {
	migrateCmd.Flags().BoolVar(&up, "up", false, "Run migrations up")
	migrateCmd.Flags().BoolVar(&down, "down", false, "Run migrations down")
	RootCmd.AddCommand(migrateCmd)
}
