package main

import (
	"fmt"
	"log/slog"

	"github.com/urfave/cli/v2"
)

type appMode string

const (
	appModeProduction  appMode = "production"
	appModeDevelopment appMode = "development"
)

func (m appMode) String() string {
	return string(m)
}

var (
	appFlagMode = &cli.GenericFlag{
		Name: "mode",
		Value: &EnumValue{
			Enum:    []string{appModeDevelopment.String(), appModeProduction.String()},
			Default: appModeDevelopment.String(),
		},
		Usage:   fmt.Sprintf("%s or %s", appModeProduction, appModeDevelopment),
		EnvVars: []string{"APP_MODE"},
	}
	appFlags = []cli.Flag{
		appFlagMode,
	}
)

type appWrapper struct {
	*cli.App
	logger *slog.Logger
}

func newApp(name, version string) *appWrapper {
	app := &appWrapper{App: cli.NewApp(), logger: slog.Default()}
	app.Name = name
	app.HelpName = name
	app.Version = version
	app.Commands = []*cli.Command{cmdDB, cmdJob, cmdConsumer}
	app.Flags = concatSlices(appFlags, logFlags)
	app.Before = app.handleBefore
	return app
}

func (a *appWrapper) handleBefore(c *cli.Context) error {
	a.logger = newLoggerFromFlags(c)

	c.Context = loggerToCtx(c.Context, a.logger)

	a.logger.Debug("executing command", slog.Any("args", c.Args().Slice()))

	return nil
}
