package s2s

import (
	"net/http"

	s2sEvents "code.justin.tv/sse/malachai/pkg/events"
	s2sCallee "code.justin.tv/sse/malachai/pkg/s2s/callee"
	"github.com/pkg/errors"

	"code.justin.tv/eventbus/controlplane/internal/logger"
	"code.justin.tv/eventbus/controlplane/internal/logger/s2slog"
)

func Middleware(l *logger.Logger, serviceName string) (func(http.Handler) http.Handler, error) {
	eventLogger, err := s2sEvents.NewEventLogger(s2sEvents.Config{}, s2slog.FromZapLogger(l.Logger))
	if err != nil {
		return nil, errors.Wrap(err, "failed to initialize s2s event writer")
	}
	s2sClient := &s2sCallee.Client{
		ServiceName:        serviceName,
		EventsWriterClient: eventLogger,
		Logger:             s2slog.FromZapLogger(l.Logger),
		Config: &s2sCallee.Config{
			DisableStatsClient: true,
		},
	}
	err = s2sClient.Start()
	if err != nil {
		return nil, errors.Wrap(err, "failed to start s2s")
	}
	return func(next http.Handler) http.Handler {
		return s2sClient.RequestValidatorMiddleware(next)
	}, nil
}
