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/infrastructure/rpc"
)

func init() {
	createSubscriberGrant.Flags().StringVarP(&createSubGrantEnvironment, "environment", "e", "", "event stream environment to grant publisher access to")
	createSubscriberGrant.MarkFlagRequired("environment")

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

	createSubscriberGrant.Flags().StringVarP(&createSubGrantIAMRole, "iam-role", "r", "", "service id being given publisher access")
	createSubscriberGrant.MarkFlagRequired("iam-role")

	createSubscriberGrant.Flags().StringVarP(&createSubGrantMessageName, "message-name", "m", "", "service id being given publisher access")
	createSubscriberGrant.MarkFlagRequired("message-name")

	createSubscriberGrant.Flags().StringVarP(&createSubGrantFieldName, "field-name", "f", "", "service id being given publisher access")
	createSubscriberGrant.MarkFlagRequired("field-name")

	rootCmd.AddCommand(createSubscriberGrant)
}

var createSubGrantIAMRole string
var createSubGrantEventType string
var createSubGrantEnvironment string
var createSubGrantMessageName string
var createSubGrantFieldName string

var createSubscriberGrant = &cobra.Command{
	Use:   "create-subscriber-grant",
	Short: "Grants a subscriber access to an authorized field",
	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 {
			fmt.Printf("could not create client: %v\n", err)
			os.Exit(1)
		}
		_, err = c.CreateAuthorizedFieldSubscriberGrant(ctx, &rpc.CreateAuthorizedFieldSubscriberGrantReq{
			IamRole:     createSubGrantIAMRole,
			EventType:   createSubGrantEventType,
			Environment: createSubGrantEnvironment,
			AuthorizedField: &rpc.AuthorizedField{
				MessageName: createSubGrantMessageName,
				FieldName:   createSubGrantFieldName,
			},
		})
		if err != nil {
			fmt.Printf("could not create authorized field subscriber grant: %v\n", err)
		}
		fmt.Printf("Created subscriber grant\n----------------\nIAM Role:\t%s\nEvent Type:\t%s\nEnvironment:\t%s\nMessage Name:\t%s\nField Name:\t%s\n",
			createSubGrantIAMRole,
			createSubGrantEventType,
			createSubGrantEnvironment,
			createSubGrantMessageName,
			createSubGrantFieldName,
		)
	},
}
