package dummy

import (
	"html/template"
	"net/http"

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

	_ "embed"
)

var (
	//go:embed index.gohtml
	indexTmpl string
)

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

	return &cli.Command{
		Name:        "run",
		Usage:       "Run the dummy server",
		Description: "The dummy server is a very basic web application allowing the debug of incoming requests",
		Flags: append(flags, &cli.StringFlag{
			Name:  "address",
			Usage: "the dummy server listening address",
			Value: ":8082",
		}),
		Action: func(ctx *cli.Context) error {
			address := ctx.String("address")

			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))

			tmpl, err := template.New("").Parse(indexTmpl)
			if err != nil {
				return errors.WithStack(err)
			}

			handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				data := struct {
					Request *http.Request
				}{
					Request: r,
				}

				if err := tmpl.Execute(w, data); err != nil {
					logger.Error(ctx.Context, "could not execute template", logger.CapturedE(errors.WithStack(err)))
				}
			})

			logger.Info(ctx.Context, "listening", logger.F("address", address))

			if err := http.ListenAndServe(address, handler); err != nil {
				return errors.WithStack(err)
			}

			return nil
		},
	}
}