package proxy

import (
	"fmt"
	"strings"
	"time"

	"forge.cadoles.com/cadoles/bouncer/internal/command/common"
	"forge.cadoles.com/cadoles/bouncer/internal/proxy"
	"forge.cadoles.com/cadoles/bouncer/internal/setup"
	"github.com/pkg/errors"
	"github.com/urfave/cli/v2"
	"gitlab.com/wpetit/goweb/logger"
)

func RunCommand() *cli.Command {
	flags := common.Flags()

	return &cli.Command{
		Name:  "run",
		Usage: "Run the proxy server",
		Flags: flags,
		Action: func(ctx *cli.Context) error {
			conf, err := common.LoadConfig(ctx)
			if err != nil {
				return errors.Wrap(err, "could not load configuration")
			}

			logger.SetFormat(logger.Format(conf.Logger.Format))
			logger.SetLevel(logger.Level(conf.Logger.Level))

			logger.Debug(ctx.Context, "using config", logger.F("config", conf))

			projectVersion := ctx.String("projectVersion")

			if conf.Proxy.Sentry.DSN != "" {
				flushSentry, err := setup.SetupSentry(ctx.Context, conf.Proxy.Sentry, projectVersion)
				if err != nil {
					return errors.Wrap(err, "could not initialize sentry client")
				}

				defer flushSentry()
			}

			layers, err := setup.GetLayers(ctx.Context, conf)
			if err != nil {
				return errors.Wrap(err, "could not initialize director layers")
			}

			srv := proxy.NewServer(
				proxy.WithServerConfig(conf.Proxy),
				proxy.WithRedisConfig(conf.Redis),
				proxy.WithDirectorLayers(layers...),
				proxy.WithDirectorCacheTTL(time.Duration(*conf.Proxy.Cache.TTL)),
			)

			addrs, srvErrs := srv.Start(ctx.Context)

			select {
			case addr := <-addrs:
				url := fmt.Sprintf("http://%s", addr.String())
				url = strings.Replace(url, "0.0.0.0", "127.0.0.1", 1)

				logger.Info(ctx.Context, "listening", logger.F("url", url))
			case err = <-srvErrs:
				return errors.WithStack(err)
			}

			if err = <-srvErrs; err != nil {
				return errors.WithStack(err)
			}

			return nil
		},
	}
}