package middleware

import (
	"net/http"
	"strings"

	"github.com/acp/interceptor/internal/tracing"
	"github.com/acp/interceptor/internal/utils"
	"github.com/gin-gonic/gin"
)

// APIKeyAuth optionally enforces X-API-Key when API_KEY is configured.
func APIKeyAuth(apiKey string) gin.HandlerFunc {
	if strings.TrimSpace(apiKey) == "" {
		return func(c *gin.Context) {
			c.Next()
		}
	}

	return func(c *gin.Context) {
		traceID := tracing.TraceIDFromContext(c)
		got := strings.TrimSpace(c.GetHeader("X-API-Key"))
		if got == "" || got != apiKey {
			utils.AbortWithErrorJSON(c, http.StatusUnauthorized, traceID, "unauthorized")
			return
		}
		c.Next()
	}
}
