package api

import (
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
	"net/http"
	"os"
	"thuanle.me/ip-info/configs"
	"thuanle.me/ip-info/configs/key"
	"time"
)

var srv *http.Server

func StartApiService() {
	log.Info().Msg("Starting API service")

	engine := gin.Default()

	trustedProxyIP := os.Getenv(key.EnvGinTrustedProxyIp)
	if trustedProxyIP != "" {
		_ = engine.SetTrustedProxies([]string{trustedProxyIP})
	}

	engine.GET("/", HandleMyIp)
	engine.GET("/json", HandleJson)
	engine.GET("/metrics", HandleMetrics)
	engine.GET("/:ip", HandleOtherIp)

	port := os.Getenv(key.EnvApiPort)
	if len(port) == 0 {
		port = configs.ApiDefaultPort
	}
	srv = &http.Server{
		Addr:    ":" + port,
		Handler: engine,
	}

	go func() {
		// service connections
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal().Err(err).Msg("Error running API service")
		}
	}()

	log.Info().Str("port", port).Msg("API service started")

}

func Shutdown() {
	// Graceful shutdown: let in-flight requests finish (bounded by a timeout)
	// instead of abruptly closing connections.
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Err(err).Msg("Error shutting down API service")
	}
	log.Info().Msg("API service stopped")
}
