package http

import (
	"actatempus_backend/internal/application/services"
	"actatempus_backend/internal/infrastructure/config"
	"net/http"
	"strings"

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

type Server struct {
	cfg                *config.Config
	userService        *services.UserService
	projectService     *services.ProjectService
	projectTaskService *services.ProjectTaskService
	timeEntryService   *services.TimeEntryService
	authService        *services.AuthService
}

// NewServer initializes the Server with its dependencies.
func NewServer(
	cfg *config.Config,
	userService *services.UserService,
	projectService *services.ProjectService,
	projectTaskService *services.ProjectTaskService,
	timeEntryService *services.TimeEntryService,
	authService *services.AuthService,
) *Server {
	return &Server{
		cfg:                cfg,
		userService:        userService,
		projectService:     projectService,
		projectTaskService: projectTaskService,
		timeEntryService:   timeEntryService,
		authService:        authService,
	}
}

func (s *Server) Start() error {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "Welcome to ActaTempus!",
		})
	})
	// Health Check
	r.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "Server is running",
		})
	})

	// Register Service Routes
	api := r.Group("/api")
	{
		userRouter := api.Group("/users")
		s.userService.RegisterRoutes(userRouter)

		projectRouter := api.Group("/projects")
		s.projectService.RegisterRoutes(projectRouter)

		projectTaskRouter := api.Group("/project-tasks")
		s.projectTaskService.RegisterRoutes(projectTaskRouter)

		timeEntryRouter := api.Group("/time-entries")
		s.timeEntryService.RegisterRoutes(timeEntryRouter)

		authRouter := api.Group("/auth")
		s.authService.RegisterRoutes(authRouter)
	}

	port := s.cfg.Port
	if !strings.HasPrefix(port, ":") {
		port = ":" + port // Add the colon if it's missing
	}
	return r.Run(port) // Start the server on the configured port
}
