package command

import (
	"context"
	"git.gocasts.ir/ebhomengo/niki/benefactorapp"
	"git.gocasts.ir/ebhomengo/niki/pkg/logger"
	"github.com/spf13/cobra"
)

var migrateUp bool
var migrateDown bool

var serveCmd = &cobra.Command{
	Use:   "serve",
	Short: "Start the benefactor service",
	Long:  `This command starts the main benefactor service.`,
	Run: func(cmd *cobra.Command, args []string) {
		serve()
	},
}

func serve() {
	var cfg = loadAppConfig()

	// Initialize logger
	logger.Init(cfg.Logger)
	log := logger.L()

	db := getDB(cfg.MySQLDB)
	migrate()

	// Start the server
	log.Info("Starting benefactor Service...")

	// Connect to the database
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	app := benefactorapp.Setup(ctx, cfg, *db)
	app.Start()
}

func init() {
	serveCmd.Flags().BoolVar(&migrateUp, "migrate-up", false, "Run migrations up before starting the server")
	serveCmd.Flags().BoolVar(&migrateDown, "migrate-down", false, "Run migrations down before starting the server")
	RootCmd.AddCommand(serveCmd)
}
