// Package middleware 中间件
package middleware

import (
	"strings"

	"server/common"
	"server/modules/system/service"

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

// 白名单路径 (不需要登录即可访问)
var whiteList = []string{
	"/api/sys/auth/login",
	"/api/sys/auth/register",
	"/api/user/auth/login",
	"/api/user/auth/register",
	"/swagger/",
	"/swagger/index.html",
}

// AuthMiddleware 登录鉴权中间件
// 类似Java中的Shiro Filter
func AuthMiddleware() gin.HandlerFunc {
	userService := service.NewSysUserService()

	return func(c *gin.Context) {
		path := c.Request.URL.Path

		// 检查是否在白名单中
		for _, white := range whiteList {
			if strings.HasPrefix(path, white) {
				c.Next()
				return
			}
		}

		// 获取Token
		token := c.GetHeader(common.TokenHeader)
		if token == "" {
			common.Error(c, 401, "未登录")
			c.Abort()
			return
		}

		// 如果有前缀则处理前缀
		if common.HeaderTokenPrefix != "" && strings.HasPrefix(token, common.HeaderTokenPrefix) {
			token = token[len(common.HeaderTokenPrefix):]
		}

		// 验证Token并获取用户信息
		loginUser, err := userService.GetLoginUser(token)
		if err != nil {
			common.Error(c, 401, "登录已失效，请重新登录")
			c.Abort()
			return
		}

		// 存入上下文
		c.Set(common.ContextUserKey, loginUser)

		c.Next()
	}
}

// AddWhiteList 添加白名单路径
func AddWhiteList(paths ...string) {
	whiteList = append(whiteList, paths...)
}
