package shared

import (
	"errors"

	"github.com/gruntwork-io/terragrunt/internal/cli/flags"
	"github.com/gruntwork-io/terragrunt/internal/clihelper"
	"github.com/gruntwork-io/terragrunt/pkg/options"
)

const (
	ParallelismFlagName = "parallelism"
)

var (
	errInvalidParallelism = errors.New("must be positive")
)

// NewParallelismFlag creates a flag for specifying parallelism level.
func NewParallelismFlag(opts *options.TerragruntOptions) *flags.Flag {
	tgPrefix := flags.Prefix{flags.TgPrefix}
	terragruntPrefix := flags.Prefix{flags.TerragruntPrefix}

	return flags.NewFlag(
		&clihelper.GenericFlag[int]{
			Name:        ParallelismFlagName,
			EnvVars:     tgPrefix.EnvVars(ParallelismFlagName),
			Destination: &opts.Parallelism,
			Usage:       "Parallelism for --all commands.",
			Setter: func(value int) error {
				if value <= 0 {
					return errInvalidParallelism
				}

				return nil
			},
		},
		flags.WithDeprecatedEnvVars(terragruntPrefix.EnvVars("parallelism"), opts.StrictControls),
	)
}
