package command

import (
	"log"
	"os"
	"path/filepath"

	"git.gocasts.ir/ebhomengo/niki/repository/migrator"
	"git.gocasts.ir/ebhomengo/niki/repository/mysql"
	"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 product service.`,
	Run: func(cmd *cobra.Command, args []string) {
		migrate()
	},
}

func migrate() {
	workingDir, err := os.Getwd()
	if err != nil {
		log.Fatalf("Error getting working directory: %v", err)
	}

	migrationPath := filepath.Join(workingDir, "productapp", "repository", "migrations")

	// to run migrations when you want to run product service locally
	if path := os.Getenv("MIGRATION_PATH"); path != "" {
		migrationPath = path
		log.Printf("Using override migration path: %s", migrationPath)
	} else {
		log.Printf("Using default migration path: %s", migrationPath)
	}

	// TODO: Load config from environment or config file
	mgr := migrator.New(migrator.Config{
		MysqlConfig: mysql.Config{
			Username: getEnv("DB_USERNAME", "root"),
			Password: getEnv("DB_PASSWORD", ""),
			Port:     3306,
			Host:     getEnv("DB_HOST", "localhost"),
			DBName:   getEnv("DB_NAME", "niki_db"),
		},
		MigrationPath:   migrationPath,
		MigrationDBName: "product_migrations",
	})

	if up {
		mgr.Up()
	} else if down {
		mgr.Down()
	} else {
		log.Println("Please specify a migration direction with --up or --down")
	}
}

func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

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