package modules

import (
	"context"
	"runtime"
	"strings"
	"time"

	"git.frostfs.info/TrueCloudLab/frostfs-s3-gw/internal/version"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// rootCmd represents the base command when called without any subcommands.
var rootCmd = &cobra.Command{
	Use:           "frostfs-s3-authmate",
	Version:       version.Version,
	Short:         "FrostFS S3 Authmate",
	Long:          "Helps manage delegated access via gates to data stored in FrostFS network",
	Example:       "frostfs-s3-authmate --version",
	SilenceErrors: true,
	SilenceUsage:  true,
	PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
		viper.AutomaticEnv()
		viper.SetEnvPrefix("AUTHMATE")
		viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
		viper.AllowEmptyEnv(true)

		return viper.BindPFlags(cmd.Flags())
	},
	RunE: func(cmd *cobra.Command, _ []string) error {
		return cmd.Help()
	},
}

const (
	withLogFlag = "with-log"
	debugFlag   = "debug"
	timeoutFlag = "timeout"
)

func Execute(ctx context.Context) (*cobra.Command, error) {
	return rootCmd.ExecuteContextC(ctx)
}

func init() {
	rootCmd.PersistentFlags().Bool(withLogFlag, false, "Enable logger")
	rootCmd.PersistentFlags().Bool(debugFlag, false, "Enable debug logger level")
	rootCmd.PersistentFlags().Duration(timeoutFlag, time.Minute, "Timeout of processing of the command, for example 2m (note: max time unit is an hour so to set a day you should use 24h)")

	cobra.AddTemplateFunc("runtimeVersion", runtime.Version)
	rootCmd.SetVersionTemplate(`Frostfs S3 Authmate
{{printf "Version: %s" .Version }}
GoVersion: {{ runtimeVersion }}
`)

	rootCmd.AddCommand(issueSecretCmd)
	initIssueSecretCmd()

	rootCmd.AddCommand(obtainSecretCmd)
	initObtainSecretCmd()

	rootCmd.AddCommand(generatePresignedURLCmd)
	initGeneratePresignedURLCmd()

	rootCmd.AddCommand(updateSecretCmd)
	initUpdateSecretCmd()
}