package server

import (
	"fmt"

	"github.com/getsentry/sentry-go"
	"github.com/labstack/echo/v4"
)

func SentryTracingMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		ctx := c.Request().Context()
		hub := sentry.GetHubFromContext(ctx)
		if hub == nil {
			// Check the concurrency guide for more details: https://docs.sentry.io/platforms/go/concurrency/
			hub = sentry.CurrentHub().Clone()
			ctx = sentry.SetHubOnContext(ctx, hub)
		}

		options := []sentry.SpanOption{
			// Set the OP based on values from https://develop.sentry.dev/sdk/performance/span-operations/
			sentry.WithOpName("http.server"),
			sentry.ContinueFromRequest(c.Request()),
			sentry.WithTransactionSource(sentry.SourceURL),
		}

		transaction := sentry.StartTransaction(ctx,
			fmt.Sprintf("%s %s", c.Request().Method, c.Request().URL.Path),
			options...,
		)

		defer transaction.Finish()
		return next(c)
	}
}
