package cmd

import (
	"fmt"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/user-management-system/internal/config"
	"github.com/user-management-system/internal/server"
)

var (
	servePort string
)

// serveCmd is the serve subcommand
var serveCmd = &cobra.Command{
	Use:   "serve",
	Short: "Start the UMS server",
	Long:  `Start the User Management System HTTP server using config.yaml`,
	RunE: func(cmd *cobra.Command, args []string) error {
		// 设置配置文件路径
		viper.SetConfigFile(cfgFile)

		// 加载配置
		cfg, err := config.Load()
		if err != nil {
			return fmt.Errorf("load config failed: %w", err)
		}

		// 允许通过 --port 覆盖配置
		if servePort != "" {
			var portInt int
			if _, err := fmt.Sscanf(servePort, "%d", &portInt); err != nil {
				return fmt.Errorf("invalid port: %w", err)
			}
			cfg.Server.Port = portInt
		}

		// 启动服务器
		return server.Serve(cfg)
	},
}

func init() {
	serveCmd.Flags().StringVar(&servePort, "port", "", "server port (overrides config)")
	rootCmd.AddCommand(serveCmd)
}
