package s2s2

import (
	"net/http"

	"code.justin.tv/amzn/TwitchS2S2/internal/opwrap"
	"code.justin.tv/video/metrics-middleware/v2/operation"
)

// passthroughableHandler implements Handler.
type passthroughableHandler struct {
	http.Handler
	PassthroughHandler http.Handler
	OperationStarter   *operation.Starter
}

// Returns a handler to use for onboarding services with existing production
// traffic. This will check authentication and authorization only if the
// Authorization header is provided.
func (h *passthroughableHandler) PassthroughIfAuthorizationNotPresented() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if len(r.Header.Get("Authorization")) == 0 {
			ctx, op := h.OperationStarter.StartOp(r.Context(), opwrap.ServePassthroughRequest)
			defer opwrap.EndWithError(op, nil)

			h.PassthroughHandler.ServeHTTP(w, r.WithContext(ctx))
			return
		}
		h.Handler.ServeHTTP(w, r)
	})
}
