package cmd

import (
	"context"
	"fmt"
	"os"

	"code.justin.tv/eventbus/admin-cli/internal/output"

	"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() {
	getCloudFormationVersionCommand.Flags().StringVarP(&iamRole, "iam-role", "r", "", "iam role to check the account of")
	getCloudFormationVersionCommand.MarkFlagRequired("iam-role")
}

var iamRole string

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

var getCloudFormationVersionCommand = &cobra.Command{
	Use:   "get-cloudformation-version",
	Short: "Gets the installed CloudFormation version for the account owning the given role",
	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)
		}

		resp, err := c.GetCloudFormationVersion(ctx,
			&rpc.GetCloudFormationVersionReq{
				IamRole: &rpc.IAMRole{
					Arn: iamRole,
				},
			},
		)
		if err != nil {
			output.FatalError(err)
		}

		output.MapMsg("CloudFormation Version", map[string]string{
			"IAM Role": iamRole,
			"Version":  resp.GetVersion(),
		})
	},
}
