package command

import (
	cfgloader "git.gocasts.ir/ebhomengo/niki/pkg/cfg_loader"
	"git.gocasts.ir/ebhomengo/niki/pkg/path"
	"git.gocasts.ir/ebhomengo/niki/shoppingbasketapp"
	"github.com/spf13/cobra"
	"log"
	"os"
	"path/filepath"
)

var RootCmd = &cobra.Command{
	Use:   "shoppingbasket_service",
	Short: "A CLI for shoppingbasket service",
	Long: `shoppingbasket Service CLI is a tool to manage and run 
the shoppingbasket service, including migrations and server startup.`,
}

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

	projectRoot, err := path.PathProjectRoot()
	if err != nil {
		log.Fatalf("error finding project root: %v", err)
	}

	yamlPath := os.Getenv("CONFIG_PATH")

	if yamlPath == "" {
		defaultConfig := filepath.Join(projectRoot, "deploy", "shoppingbasket", "development", "config.yml")
		if _, err := os.Stat(defaultConfig); err == nil {
			yamlPath = defaultConfig
		} else {
			yamlPath = filepath.Join(projectRoot, "deploy", "shoppingbasket", "development", "config.local.yml")
		}
	}

	options := cfgloader.Option{
		Prefix:       "SHOPPINGBASKET_",
		Delimiter:    ".",
		Separator:    "__",
		YamlFilePath: yamlPath,
		CallbackEnv:  nil,
	}

	if err := cfgloader.Load(options, &cfg); err != nil {
		log.Fatalf("Failed to load benefactor config: %v", err)
	}

	return cfg
}
