package iamrole

import (
	"context"
	"log"

	"github.com/spf13/cobra"

	"code.justin.tv/eventbus/controlplane/rpc"

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

var iamRoleDeleteARN string

func init() {
	iamRoleDeleteCommand.Flags().StringVarP(&iamRoleDeleteARN, "role-arn", "r", "", "ARN of IAM role to delete")
	iamRoleDeleteCommand.MarkFlagRequired("role-arn")
}

var iamRoleDeleteCommand = &cobra.Command{
	Use:   "delete",
	Short: "Deletes an existing IAM role",
	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.NewServices(config)
		if err != nil {
			log.Fatal("Error creating services client: ", err.Error())
		}

		_, err = c.DeleteIAMRole(ctx, &rpc.DeleteIAMRoleReq{
			Arn: iamRoleDeleteARN,
		})
		if err != nil {
			log.Fatal("Error deleting IAM role: ", err.Error())
		}

		output.MapMsg("Deleted IAM role", map[string]string{
			"ARN": iamRoleDeleteARN,
		})
		output.Newline()
	},
}
