package router

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/mhaya/game/game_cluster/internal/constant"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"go.mongodb.org/mongo-driver/bson"

	"github.com/gin-gonic/gin"
	"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 {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"msg": "token is empty",
			})
			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()
		ss, _ := mdb.RDB.HGet(context.Background(), "admin::token::"+tokenString, constant.AdminAccess).Result()
		fmt.Println(ss)
		// 检查是否有权限
		if s == "" && result == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"msg": "token is no auth",
			})
			return
		}
		if result == "" {
			if err := checkIP(c); err != nil {
				c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
					"msg": "ip is no auth",
				})
				return
			}
		}
		c.Next()
	}
}

// checkIP
func checkIP(c *gin.Context) error {
	// 获取请求的ip
	ip := c.ClientIP()
	whitelistModel := &models.Whitelist{}
	collection := mdb.MDB.Collection(whitelistModel.TableName())

	// 设置超时时间
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel() // 确保在函数退出时取消上下文

	// 示例：查询 IP 是否在白名单中
	err := collection.FindOne(ctx, bson.M{"ip": ip}).Decode(&whitelistModel)
	if err != nil {
		// 处理查询错误
		return fmt.Errorf("failed to check IP in whitelist: %w", err)
	}
	// 根据查询结果决定是否允许访问
	if whitelistModel != nil {
		return nil // 允许访问
	} else {
		return errors.New("IP not in whitelist") // 拒绝访问
	}
}
