package middleware

import (
	"net/http"
	"xboard-go/internal/service"

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

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

		if token == "" || nodeID == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"message": "missing node credentials"})
			c.Abort()
			return
		}

		if !service.IsValidServerType(nodeType) {
			c.JSON(http.StatusBadRequest, gin.H{"message": "invalid node type"})
			c.Abort()
			return
		}

		serverToken := service.MustGetString("server_token", "")
		if serverToken == "" {
			c.JSON(http.StatusInternalServerError, gin.H{"message": "server_token is not configured"})
			c.Abort()
			return
		}

		if token != serverToken {
			c.JSON(http.StatusUnauthorized, gin.H{"message": "invalid server token"})
			c.Abort()
			return
		}

		node, err := service.FindServer(nodeID, nodeType)
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{"message": "server not found"})
			c.Abort()
			return
		}

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