//go:build ignore

package middleware

import (
	"net/http"
	"xboard-go/internal/database"
	"xboard-go/internal/model"

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

func NodeAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Query("token")
		nodeID := c.Query("node_id")
		nodeType := c.Query("node_type")

		if token == "" || nodeID == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"message": "缺少认证信息"})
			c.Abort()
			return
		}

		// Check server_token from settings
		var setting model.Setting
		if err := database.DB.Where("name = ?", "server_token").First(&setting).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"message": "系统配置错误"})
			c.Abort()
			return
		}

		if token != setting.Value {
			c.JSON(http.StatusUnauthorized, gin.H{"message": "无效的Token"})
			c.Abort()
			return
		}

		// Get node info
		var node model.Server
		if err := database.DB.Where("id = ? AND type = ?", nodeID, nodeType).First(&node).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"message": "节点不存在"})
			c.Abort()
			return
		}

		c.Set("node", &node)
		c.Next()
	}
}
