package featureflag

import (
	"context"
	"log"
	"strconv"

	"github.com/spf13/cobra"

	"code.justin.tv/eventbus/admin-cli/internal/client"
	"code.justin.tv/eventbus/admin-cli/internal/environment"
	"code.justin.tv/eventbus/admin-cli/internal/output"
	"code.justin.tv/eventbus/controlplane/rpc"
)

var featureFlagCreateName string
var featureFlagCreateIsEnabled bool

func init() {
	featureFlagCreateCommand.Flags().StringVarP(&featureFlagCreateName, "name", "n", "", "name of feature flag")
	featureFlagCreateCommand.MarkFlagRequired("name")

	featureFlagCreateCommand.Flags().BoolVarP(&featureFlagCreateIsEnabled, "enabled", "e", false, "status of created feature flag (true=enabled)")
}

var featureFlagCreateCommand = &cobra.Command{
	Use:   "create",
	Short: "Creates a new feature flag",
	Run: func(cmd *cobra.Command, args []string) {
		ctx := context.Background()
		config, err := environment.Resolve()
		if err != nil {
			log.Fatal("Error resolving runtime environment: ", err.Error())
		}

		c, err := client.NewFeatureFlags(config)
		if err != nil {
			log.Fatal("Error creating feature flags client: ", err.Error())
		}

		_, err = c.Create(ctx, &rpc.CreateFeatureFlagsReq{
			FeatureFlag: &rpc.FeatureFlag{
				Name:      featureFlagCreateName,
				IsEnabled: featureFlagCreateIsEnabled,
			},
		})
		if err != nil {
			log.Fatal("Error creating feature flag: ", err.Error())
		}

		output.MapMsg("Created feature flag", map[string]string{
			"Name":    featureFlagCreateName,
			"Enabled": strconv.FormatBool(featureFlagCreateIsEnabled),
		})
		output.Newline()
	},
}
