package cmd

import (
	"context"
	"fmt"
	"os"

	"github.com/spf13/cobra"

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

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

func init() {

	authorizePublisherCommand.Flags().StringVarP(&authorizePublisherEnvironment, "environment", "e", "", "event stream environment to grant publisher access to")
	authorizePublisherCommand.MarkFlagRequired("region")

	authorizePublisherCommand.Flags().StringVarP(&authorizePublisherEventType, "event-type", "t", "", "event type to grant publisher access to")
	authorizePublisherCommand.MarkFlagRequired("event-type")

	authorizePublisherCommand.Flags().StringVarP(&authorizePublisherIAMRole, "iam-role", "r", "", "IAM role being given publisher access")
	authorizePublisherCommand.MarkFlagRequired("event-type")

	rootCmd.AddCommand(authorizePublisherCommand)
}

var authorizePublisherEnvironment string
var authorizePublisherEventType string
var authorizePublisherIAMRole string

var authorizePublisherCommand = &cobra.Command{
	Use:   "authorize-publisher",
	Short: "Grants a publisher the ability to publish to an event stream, including the ability to encrypt authorized fields",
	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.NewInfrastructure(config)
		if err != nil {
			panic(err)
		}

		_, err = c.AllowIAMRolePublish(ctx, &rpc.AllowIAMRolePublishReq{
			EventType:   authorizePublisherEventType,
			Environment: authorizePublisherEnvironment,
			IamRole:     authorizePublisherIAMRole,
		})
		if err != nil {
			panic(err)
		}

		fmt.Printf("Publisher authorized\n----------------\nIAM Role:\t%s\nEvent Type:\t%s\nEnvironment:\t%s\n", authorizePublisherIAMRole, authorizePublisherEventType, authorizePublisherEnvironment)
	},
}
