package document_scraper

import (
	"crypto/subtle"
	"strings"
	"tm/pkg/response"

	"github.com/labstack/echo/v4"
)

// APIKeyMiddleware validates the API key for service-to-service authentication
func APIKeyMiddleware(apiKey string) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			// Extract API key from X-API-Key header
			apiKeyHeader := c.Request().Header.Get("X-API-Key")
			if apiKeyHeader == "" {
				// Also check Authorization header with "ApiKey <key>" format
				authHeader := c.Request().Header.Get("Authorization")
				if strings.HasPrefix(authHeader, "ApiKey ") {
					apiKeyHeader = strings.TrimPrefix(authHeader, "ApiKey ")
				}
			}

			if apiKeyHeader == "" {
				return response.Unauthorized(c, "API key required. Use X-API-Key header or Authorization: ApiKey <key>")
			}

			if subtle.ConstantTimeCompare([]byte(apiKeyHeader), []byte(apiKey)) != 1 {
				return response.Unauthorized(c, "Invalid API key")
			}

			return next(c)
		}
	}
}
