package featureflag

import (
	"context"
	"log"
	"os"
	"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"
	"github.com/olekukonko/tablewriter"
)

var featureFlagListCommand = &cobra.Command{
	Use:   "list",
	Short: "Lists existing feature flags",
	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())
		}

		resp, err := c.List(ctx, &rpc.ListFeatureFlagsReq{})
		if err != nil {
			log.Fatal("Error fetching feature flags: ", err.Error())
		}

		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"Name", "Enabled"})

		for _, ff := range resp.GetFeatureFlags() {
			table.Append([]string{ff.GetName(), strconv.FormatBool(ff.GetIsEnabled())})
		}

		table.Render() // Send output
		output.Newline()
	},
}
