package command

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

var migrateUp bool
var migrateDown bool

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

func serve() {
	var cfg shoppingbasketapp.Config = loadAppConfig()

	logger.Init(cfg.Logger)
	l := logger.L()

	l.Info("Starting shoppingbasket service...")

	migrate()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	app, err := shoppingbasketapp.Setup(ctx, cfg)
	if err != nil {
		l.Error("failed initialize shopping basket app", "error", err)
		log.Fatalf(fmt.Sprintf("error starting shopping basket app: %v", err))
	}

	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")
	ServeCmd.MarkFlagsMutuallyExclusive("migrate-up", "migrate-down")
	RootCmd.AddCommand(ServeCmd)
}
