package router

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/mhaya/game/game_cluster/internal/constant"
	"github.com/mhaya/game/game_cluster/internal/mdb"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("Token")
		if tokenString == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"msg": "token is empty",
			})
			return
		}
		result, err := mdb.RDB.Get(context.Background(), tokenString).Result()
		if err != nil {
			return
		}
		if result == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"msg": "token is invalid",
			})
			return
		}
		// 获取请求URL
		url := c.Request.URL.Path
		s, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, url).Result()
		admin, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, constant.AdminAccess).Result()
		// 检查是否有权限
		if s == "" && admin == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"msg": "token is no auth",
			})
			return
		}
		c.Next()
	}
}
