package middleware

import (
	"crypto/subtle"
	"net/http"

	"mengyamonitor-backend-server/internal/config"

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

// AdminToken rejects requests without a valid X-Admin-Token header.
func AdminToken(cfg *config.Config) gin.HandlerFunc {
	tok := []byte(cfg.AdminToken)
	return func(c *gin.Context) {
		given := []byte(c.GetHeader("X-Admin-Token"))
		if subtle.ConstantTimeCompare(given, tok) != 1 {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
			return
		}
		c.Next()
	}
}
