package httpserver

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

	"warpbox.dev/backend/libs/config"
	"warpbox.dev/backend/libs/handlers"
	"warpbox.dev/backend/libs/jobs"
	"warpbox.dev/backend/libs/middleware"
	"warpbox.dev/backend/libs/services"
	"warpbox.dev/backend/libs/web"
)

func New(cfg config.Config, logger *slog.Logger) (*http.Server, error) {
	renderer, err := web.NewRenderer(cfg.TemplateDir, cfg.AppName, cfg.AppVersion, cfg.BaseURL)
	if err != nil {
		return nil, err
	}

	uploadService, err := services.NewUploadService(cfg.MaxUploadSize, cfg.DataDir, cfg.BaseURL, logger)
	if err != nil {
		return nil, err
	}
	authService, err := services.NewAuthService(uploadService.DB(), cfg.BaseURL)
	if err != nil {
		uploadService.Close()
		return nil, err
	}
	settingsService, err := services.NewSettingsService(uploadService.DB(), cfg.DefaultSettings)
	if err != nil {
		uploadService.Close()
		return nil, err
	}
	stopJobs := jobs.StartAll(cfg, logger, uploadService)
	app := handlers.NewApp(cfg, logger, renderer, uploadService, authService, settingsService)

	router := http.NewServeMux()
	app.RegisterRoutes(router)

	handler := middleware.Chain(
		router,
		middleware.Recoverer(logger),
		middleware.RequestID,
		middleware.SecurityHeaders,
		middleware.Gzip,
		middleware.Logger(logger),
	)

	server := &http.Server{
		Addr:         cfg.Addr,
		Handler:      handler,
		ReadTimeout:  cfg.ReadTimeout,
		WriteTimeout: cfg.WriteTimeout,
		IdleTimeout:  cfg.IdleTimeout,
	}
	server.RegisterOnShutdown(func() {
		stopJobs()
		if err := uploadService.Close(); err != nil {
			logger.Error("failed to close upload service", "source", "shutdown", "severity", "error", "error", err.Error())
		}
	})

	return server, nil
}
