package main

import (
	"context"
	"fmt"
	"net/http"
	"os/signal"
	"syscall"
	"time"

	"<<project_name>>/core"
	"<<project_name>>/middlewares"
	"<<project_name>>/routers"

	"go.uber.org/zap"
)

var logger, sLogger = core.GetLoggers()

<% if enable_swagger %>
// @title                      <<project_name_pascal>> API
// @version                    <<cargo_version>>
// @description                <<cargo_description>>
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @BasePath                   /
<% endif %>
func main() {
	// 初始化应用
	app := core.GetApp()
	defer logger.Sync()  //nolint:errcheck
	defer sLogger.Sync() //nolint:errcheck
	globalCtx, globalCancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer globalCancel()
	app.Config.Server.Context = globalCtx
	// 创建路由器（不包含路由）
	r := routers.CreateRouter()
	// 注册中间件（必须在路由注册之前）
	middlewares.RegisterMiddlewares(r, logger)
	// 注册所有路由
	routers.RegisterAllRoutes(r)
	// 创建 HTTP 服务器
	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", app.Config.Server.Host, app.Config.Server.Port),
		Handler: r,
	}

	// 启动服务器
	go func() {
		sLogger.Infof("Server starting on %s:%d", app.Config.Server.Host, app.Config.Server.Port)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			sLogger.Fatal("Failed to start server:", zap.Error(err))
		}
	}()

	<-globalCtx.Done()
	sLogger.Info("Shutting down server...")

	// 5秒的超时时间来关闭服务器
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		sLogger.Warn("Server forced to shutdown:", zap.Error(err))
	}
	sLogger.Info("Server exited")
}
