// roll back migration
package main

import (
	"code.justin.tv/d8a/iceman/lib/dbconf"
	"code.justin.tv/d8a/iceman/lib/migrations"
	"code.justin.tv/d8a/iceman/lib/queries"
	"github.com/spf13/cobra"
)

var downCmd = &cobra.Command{
	Use:   "down",
	Short: "roll back the latest applied migration",
	Long:  "This will roll back the migration last appiled to the database.",
	RunE: func(cmd *cobra.Command, args []string) error {
		conf, err := dbconf.NewDBConf(path, env, schema, "migrations")
		if err != nil {
			return err
		}

		db, err := dbconf.OpenDBFromDBConf(conf)
		if err != nil {
			return err
		}
		defer queries.TryClose(db)

		names, err := migrations.RunMigrations(db, conf.DriverQueries, &migrations.DirectoryMigrationSource{MigrationsDirectory: conf.Dir}, false)
		if err != nil {
			return err
		}

		for _, name := range names {
			green.Printf("Successfully rolled back: %v\n", name)
		}

		return nil
	},
}

func init() {
	RootCmd.AddCommand(downCmd)
}
