package main

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

	"gitea.miguelmuniz.com/rogueking/junk2jive-server/internal/config"
	"gitea.miguelmuniz.com/rogueking/junk2jive-server/internal/logger"
	"gitea.miguelmuniz.com/rogueking/junk2jive-server/internal/router"
)

func main() {
	flags := config.DeclareFlags()
	port := config.ConfigPort(flags)

	// Set up routes
	router := router.SetupRouter(config.AllowedOrigins)
	server := config.SetupServer(port, router, flags)

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)

	go func() {
		logger.Info("Starting server on %s", port)
		err := server.ListenAndServe()
		if err != nil {
			logger.Error("Error starting server %v", err)
		}
	}()

	<-stop
	logger.Info("Shutting down gracefully...")

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

	if err := server.Shutdown(ctx); err != nil {
		logger.Error("Error shutting down HTTP server: %v", err)
	}

	logger.Info("Shutdown complete.")

}
