package http

import (
	"log/slog"
	stdhttp "net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func (h *http) createServer(name, address string) {
	engine := gin.New()
	//nolint:gomnd,mnd
	httpServer := &stdhttp.Server{
		Addr:    address,
		Handler: engine.Handler(),
		// ToDo: move into configuration.
		ReadTimeout:  time.Second * 5,
		WriteTimeout: time.Second * 10,
	}

	h.serversMutex.Lock()
	h.servers[name] = engine
	h.httpServers[name] = httpServer
	h.serversMutex.Unlock()

	// ToDo: trusted proxies.

	engine.Use(h.requestLogger(name))
}

func (h *http) startServers() {
	h.serversMutex.RLock()
	defer h.serversMutex.RUnlock()

	for srvName, httpServer := range h.httpServers {
		go func(name string, srv *stdhttp.Server) {
			slog.Info(
				"Starting HTTP server...",
				"service", subsystem,
				"server-name", name,
				"server-address", srv.Addr,
			)

			if err := srv.ListenAndServe(); err != nil {
				slog.Error(
					"Failed to start HTTP server!",
					"service", subsystem,
					"server-name", name,
					"server-address", srv.Addr,
					"error", err.Error(),
				)
			}
		}(srvName, httpServer)
	}
}
