package middleware

import (
	"log/slog"
	"net/http"
	"strings"

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

// InternalAuthMiddleware protects internal endpoints.
// - If allowAnonymous is true, bypass all token checks and log INFO.
// - If allowAnonymous is false and expectedToken is empty, reject all requests.
// - Otherwise, require X-Internal-Token header to match expectedToken.
func InternalAuthMiddleware(expectedToken string, allowAnonymous bool) gin.HandlerFunc {
	expectedToken = strings.TrimSpace(expectedToken)
	return func(c *gin.Context) {
		if allowAnonymous {
			slog.Info("internal endpoint accessed anonymously",
				"path", c.Request.URL.Path,
				"remote_addr", c.ClientIP())
			c.Next()
			return
		}

		// If token is empty and anonymous is not allowed, reject
		if expectedToken == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "internal authentication required but not configured"})
			c.Abort()
			return
		}

		token := strings.TrimSpace(c.GetHeader("X-Internal-Token"))
		if token == "" || token != expectedToken {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid internal token"})
			c.Abort()
			return
		}
		c.Next()
	}
}
