package command

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"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...")

	// TODO: Initialize database connection
	// TODO: Initialize service dependencies
	// TODO: Setup HTTP server with routes

	// Setup graceful shutdown
	go func() {
		sigCh := make(chan os.Signal, 1)
		signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
		<-sigCh
		log.Println("Shutting down Product Service gracefully...")
		os.Exit(0)
	}()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Product Service OK!")
	})

	log.Printf("Product Service listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

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