package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/spf13/cobra"
	pb "github.com/tidbcloud/config-center/proto/config_center"
	"google.golang.org/grpc"
)

// availableVersionCmd represents the cluster_config command
var availableVersionCmd = &cobra.Command{
	Use:   "available-version",
	Short: "manage available versions",
	Long:  `manage available versions`,
}

func init() {
	rootCmd.AddCommand(availableVersionCmd)

	availableVersionCmd.AddCommand(newAvailableVersionListCmd())
}

func newAvailableVersionListCmd() *cobra.Command {
	var clusterType string
	cmd := &cobra.Command{
		Use:   "list",
		Short: "get available versions",
		Long:  `get available versions`,
		RunE: func(cmd *cobra.Command, args []string) error {
			var opts []grpc.DialOption
			opts = append(opts, grpc.WithInsecure())
			conn, err := grpc.Dial(configCenterEndpoint, opts...)
			if err != nil {
				panic(err)
			}
			defer conn.Close()
			client := pb.NewConfigCenterServiceClient(conn)

			t, err := client.ListAvailableVersions(context.Background(), &pb.ListAvailableVersionsRequest{
				ClusterType: pb.ClusterType(pb.ClusterType_value[clusterType]),
			})
			if err == nil {
				txt, _ := json.MarshalIndent(t, "", "    ")
				fmt.Println(string(txt))
			}
			return err
		},
	}

	cmd.Flags().StringVarP(&clusterType, "cluster-type", "T", pb.ClusterType_DEDICATED_TIDB.String(), "cluster type")

	return cmd
}
