package command

import (
	"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 shoppingbasket service.`,
	Run: func(cmd *cobra.Command, args []string) {
		migrate()
	},
}

func migrate() {
	var cfg = loadAppConfig()

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

	migrationCfg := migrator.Config{
		MysqlConfig:     cfg.Mysql,
		MigrationPath:   cfg.PathOfMigration,
		MigrationDBName: "gorp_migrations",
	}

	if migrateUp || migrateDown {
		mgr := migrator.New(migrationCfg)
		if migrateUp {
			l.Info("Running migrations up...")
			mgr.Up()
			l.Info("Migrations up completed.")
		}
		if migrateDown {
			l.Info("Running migrations down...")
			mgr.Down()
			l.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)
}
