package setup

import (
	"context"
	"time"

	"forge.cadoles.com/cadoles/bouncer/internal/config"
	loggerWriter "forge.cadoles.com/cadoles/bouncer/internal/logger"
	"github.com/getsentry/sentry-go"
	"github.com/pkg/errors"
	"gitlab.com/wpetit/goweb/logger"
)

func SetupSentry(ctx context.Context, conf config.SentryConfig, release string) (func(), error) {
	err := sentry.Init(sentry.ClientOptions{
		Dsn:                string(conf.DSN),
		Debug:              bool(conf.Debug),
		AttachStacktrace:   bool(conf.AttachStacktrace),
		SampleRate:         float64(conf.SampleRate),
		EnableTracing:      bool(conf.EnableTracing),
		TracesSampleRate:   float64(conf.TracesSampleRate),
		ProfilesSampleRate: float64(conf.ProfilesSampleRate),
		IgnoreErrors:       conf.IgnoreErrors,
		SendDefaultPII:     bool(conf.SendDefaultPII),
		ServerName:         string(conf.ServerName),
		Release:            release,
		Environment:        string(conf.Environment),
		MaxBreadcrumbs:     int(conf.MaxBreadcrumbs),
		MaxSpans:           int(conf.MaxSpans),
		MaxErrorDepth:      int(conf.MaxErrorDepth),
		DebugWriter:        loggerWriter.NewWriter(ctx, logger.LevelDebug),
	})
	if err != nil {
		return nil, errors.WithStack(err)
	}

	logger.SetCaptureFunc(func(err error) {
		sentry.CaptureException(err)
	})

	flush := func() {
		sentry.Flush(time.Duration(*conf.FlushTimeout))
	}

	return flush, nil
}