package middleware

import (
	"errors"
	"sundynix-go/global"
	"sundynix-go/model/commom/response"
	"sundynix-go/service"
	"sundynix-go/utils/auth"
	"sundynix-go/utils/timer"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

var jwtService = service.GroupApp.SystemServiceGroup.JwtService

// AuthMiddleware 验证token有效性
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := auth.GetToken(c)
		if token == "" {
			response.NoAuth("未登录或非法访问", c)
			c.Abort()
			return
		}
		userId := auth.GetUserId(c)
		if jwtService.IsInBlacklist(userId, token) {
			response.NoAuth("未登录或令牌失效", c)
			c.Abort()
			return
		}

		j := auth.NewJWT()
		// 解析token信息
		claims, err := j.ParseToken(token)
		if err != nil {
			if errors.Is(err, auth.TokenExpired) {
				response.NoAuth("登录过期", c)
				auth.ClearToken(c)
				c.Abort()
				return
			}
			response.NoAuth(err.Error(), c)
			auth.ClearToken(c)
			c.Abort()
			return
		}
		c.Set("claims", claims)
		if claims.ExpiresAt.Unix()-time.Now().Unix() < claims.BufferTime {
			dr, _ := timer.ParseDuration(global.Config.JWT.ExpiresTime)
			claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(dr))
		}
		c.Next()
	}
}
