package infrastructure

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
)

type Server struct {
	addr string
	http.Server
	port int
}

var (
	env = os.Getenv("HTMX_APP_ENV")
)

func NewServer() *Server {
	const (
		addr = "0.0.0.0"
	)

	var port int

	if env == "production" {
		port = 8080
	} else {
		port = 8080
	}

	return &Server{
		addr,
		http.Server{
			Addr:                         addr + ":" + strconv.Itoa(port),
			Handler:                      GetRouter(),
			DisableGeneralOptionsHandler: false,
			TLSConfig:                    nil,
			ReadTimeout:                  5 * time.Second,
			ReadHeaderTimeout:            0,
			WriteTimeout:                 5 * time.Second,
			IdleTimeout:                  0,
			MaxHeaderBytes:               0,
			TLSNextProto:                 nil,
			ConnState:                    nil,
			ErrorLog:                     nil,
			BaseContext:                  nil,
			ConnContext:                  nil,
		},
		port,
	}
}

func (s *Server) Serve() {
	fmt.Printf("Starting.\nListening at %s on port %s\n", s.addr, strconv.Itoa(s.port))
	serverError := s.ListenAndServe()

	if serverError != nil {
		log.Fatal(serverError)
	}
}
