package db

import (
	"fmt"
	"strconv"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db"
	"github.com/golang-migrate/migrate/v4"
	"github.com/golang-migrate/migrate/v4/database/sqlite3"
	_ "github.com/golang-migrate/migrate/v4/source/file"
	"github.com/spf13/cobra"
)

// migrateCmd represents the db migrate command
var migrateCmd = &cobra.Command{
	Use:   "migrate",
	Short: "Run the database migrations",
	Long:  `Run the database migrations.`,
	Run: func(cmd *cobra.Command, args []string) {
		conf := utils.InitConfig("")
		up, nbSteps := parseArgs(args)
		if err := runMigrations(conf, up, nbSteps); err != nil {
			utils.Failf("Failed to run migrations: %s", err.Error())
		}
	},
}

func parseArgs(args []string) (bool, int) {
	if len(args) == 0 {
		return true, 0
	}
	var actionUp bool
	switch args[0] {
	case "up":
		actionUp = true
	case "down":
		actionUp = false
	default:
		actionUp = true
	}

	nbSteps := 0
	if len(args) > 1 {
		var err error
		nbSteps, err = strconv.Atoi(args[1])
		if err != nil {
			return actionUp, 0
		}
	}

	return actionUp, nbSteps
}

func runMigrations(conf *config.AppConfig, up bool, nbSteps int) error {
	storage, err := db.New(*conf)
	if err != nil {
		return fmt.Errorf("failed to connect to db: %w", err)
	}
	driver, err := sqlite3.WithInstance(storage.DB(), &sqlite3.Config{})
	if err != nil {
		return fmt.Errorf("failed to open sqlite3 driver: %w", err)
	}

	m, err := migrate.NewWithDatabaseInstance("file://migrations", "", driver)
	if err != nil {
		return fmt.Errorf("failed to init migrator: %w", err)
	}

	if nbSteps > 0 {
		multiplier := 1
		if !up {
			multiplier = -1
		}
		return m.Steps(multiplier * nbSteps)
	}
	if up {
		return m.Up()
	}
	return m.Down()
}

func init() {
	dbCmd.AddCommand(migrateCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// dbCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// dbCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
