package cmd

import (
	"context"
	"fmt"
	"os"

	"github.com/spf13/cobra"

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

func init() {
	rootCmd.AddCommand(listServicesCmd)
}

var listServicesCmd = &cobra.Command{
	Use:   "list-services",
	Short: "Lists registered service names and exits",
	Run: func(cmd *cobra.Command, args []string) {
		ctx := context.Background()
		config, err := environment.Resolve()
		if err != nil {
			fmt.Println("Error resolving runtime environment: ", err.Error())
			os.Exit(1)
		}

		c, err := client.NewServices(config)
		if err != nil {
			fmt.Println("Error creating controlplane client: ", err.Error())
			os.Exit(1)
		}

		services, err := c.List(ctx, &rpc.ListServicesReq{})
		if err != nil {
			fmt.Println("Error fetching services: ", err.Error())
			os.Exit(1)
		}

		fmt.Println("Got Services!")
		for _, service := range services.GetServices() {
			fmt.Println(service.GetName())
		}
	},
}
