package command

import (
	"context"
	"log"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"

	"git.gocasts.ir/ebhomengo/niki/productapp"
	"git.gocasts.ir/ebhomengo/niki/repository/mysql"
	"github.com/spf13/cobra"
)

var port string

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

func serve() {
	log.Println("Product Service Starting...")

	cfg := productapp.Config{
		HTTPServer: productapp.HTTPServerConfig{
			Port: getEnvInt("HTTP_PORT", 8080),
		},
		Database: mysql.Config{
			Username: getEnv("DB_USERNAME", "root"),
			Password: getEnv("DB_PASSWORD", ""),
			Port:     getEnvInt("DB_PORT", 3306),
			Host:     getEnv("DB_HOST", "localhost"),
			DBName:   getEnv("DB_NAME", "niki_db"),
		},
	}

	if p, err := strconv.Atoi(port); err == nil && p > 0 {
		cfg.HTTPServer.Port = p
	}

	app := productapp.Setup(cfg)

	go func() {
		app.Start()
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := app.Stop(ctx); err != nil {
		log.Fatalf("Server shutdown error: %v", err)
	}

	log.Println("Product Service stopped.")
}

func getEnvInt(key string, defaultValue int) int {
	val := os.Getenv(key)
	if val == "" {
		return defaultValue
	}
	n, err := strconv.Atoi(val)
	if err != nil {
		return defaultValue
	}
	return n
}

func init() {
	serveCmd.Flags().StringVarP(&port, "port", "p", "8080", "Port to run the server on")
	RootCmd.AddCommand(serveCmd)
}
