package httpx

import (
	"strings"

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

// RequireAdminToken returns a Gin middleware that validates Bearer <token> against the configured admin token.
func RequireAdminToken(adminToken string) gin.HandlerFunc {
	return func(c *gin.Context) {
		if adminToken == "" {
			Unauthorized(c, "Admin API is disabled: ADMIN_TOKEN is not configured")
			c.Abort()
			return
		}

		auth := c.GetHeader("Authorization")
		if auth == "" {
			Unauthorized(c, "Missing Authorization header")
			c.Abort()
			return
		}

		parts := strings.SplitN(auth, " ", 2)
		if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || parts[1] != adminToken {
			Unauthorized(c, "Invalid admin bearer token")
			c.Abort()
			return
		}

		c.Next()
	}
}
