package cmd

import (
	"fmt"
	"os"

	"github.com/perfect-panel/server/initialize"
	"github.com/perfect-panel/server/internal/config"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/pkg/conf"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/spf13/cobra"
)

func init() {
	migrateCmd.Flags().StringVar(&migrateConfigPath, "config", "etc/ppanel.yaml", "ppanel.yaml directory to read from")
	rootCmd.AddCommand(migrateCmd)
}

var (
	migrateConfigPath string
)

var migrateCmd = &cobra.Command{
	Use:   "migrate",
	Short: "Run database migrations",
	Run: func(cmd *cobra.Command, args []string) {
		runMigrate()
	},
}

func runMigrate() {
	var c config.Config
	conf.MustLoad(migrateConfigPath, &c)
	if err := logger.SetUp(c.Logger); err != nil {
		fmt.Println("Logger setup failed:", err.Error())
		os.Exit(1)
	}
	ctx := svc.NewServiceContext(c)
	initialize.Migrate(ctx)
	logger.Info("[Migrate] database migration completed")
}
