package httpserver

import (
	"time"

	"github.com/gin-gonic/gin"

	"mrcc/internal/config"
	"mrcc/pkg/response"
)

// New 创建一个配置好中间件的 Gin 实例，并注册 /health 端点。
func New(cfg *config.ServiceConfig) *gin.Engine {
	gin.SetMode(cfg.GinMode)

	r := gin.New()

	// 中间件
	r.Use(gin.Recovery())
	r.Use(gin.LoggerWithFormatter(func(p gin.LogFormatterParams) string {
		return p.TimeStamp.Format(time.RFC3339) + " | " + p.Method + " | " + p.Path + " | " +
			itoa(p.StatusCode) + " | " + p.Latency.String() + "\n"
	}))

	// CORS
	r.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})

	// 健康检查
	r.GET("/health", func(c *gin.Context) {
		response.OK(c, gin.H{
			"service": cfg.Name,
			"status":  "running",
		})
	})

	return r
}

func itoa(n int) string {
	if n == 0 {
		return "0"
	}
	buf := [10]byte{}
	pos := len(buf)
	for n > 0 {
		pos--
		buf[pos] = byte('0' + n%10)
		n /= 10
	}
	return string(buf[pos:])
}
