package server

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

	_ "github.com/joho/godotenv/autoload"

	"api-service/internal/config"
	"api-service/internal/database"
	v1 "api-service/internal/routes/v1"
)

var dbService database.Service // Global variable to hold the database service instance

type Server struct {
	port int
	db   database.Service
}

func NewServer() *http.Server {
	// Load configuration
	cfg := config.LoadConfig()
	cfg.Validate()

	port, _ := strconv.Atoi(os.Getenv("PORT"))
	if port == 0 {
		port = cfg.Server.Port
	}

	if dbService == nil { // Check if the database service is already initialized
		dbService = database.New(cfg) // Initialize only once
	}

	NewServer := &Server{
		port: port,
		db:   dbService, // Use the global database service instance
	}

	// Declare Server config
	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", NewServer.port),
		Handler:      v1.RegisterRoutes(cfg),
		IdleTimeout:  time.Minute,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 30 * time.Second,
	}

	return server
}
