package publication

import (
	"context"
	"log"

	"code.justin.tv/eventbus/admin-cli/internal/client"
	"code.justin.tv/eventbus/admin-cli/internal/environment"
	"code.justin.tv/eventbus/admin-cli/internal/output"
	"code.justin.tv/eventbus/admin-cli/internal/prompt"
	"code.justin.tv/eventbus/controlplane/infrastructure/rpc"
	"github.com/spf13/cobra"
)

var (
	envDelete, iamRoleARNDelete, eventTypeDelete string
)

func init() {
	publicationDeleteCommand.Flags().StringVarP(&envDelete, "environment", "e", "", "environment for which to delete publication for")
	publicationDeleteCommand.MarkFlagRequired("environment")
	publicationDeleteCommand.Flags().StringVarP(&iamRoleARNDelete, "iam-role", "r", "", "IAM role ARN whose publish permissions should be removed")
	publicationDeleteCommand.MarkFlagRequired("iam-role")
	publicationDeleteCommand.Flags().StringVarP(&eventTypeDelete, "event-type", "t", "", "event type to delete publication for")
	publicationDeleteCommand.MarkFlagRequired("event-type")
}

var publicationDeleteCommand = &cobra.Command{
	Use:   "delete",
	Short: "deletes a publication record in our backend",
	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.NewInfrastructure(config)
		if err != nil {
			log.Fatal("Error creating infrastructure client: ", err.Error())
		}

		passed, err := prompt.ConfirmationCheck("Provide the event type you are removing a publication for", "delete", "publication", []string{eventTypeDelete})
		if err != nil {
			log.Fatalf("Failed attempting a confirmation check: %v", err)
		} else if !passed {
			log.Fatal("Aborting due to confirmation failure")
		}

		_, err = c.DeleteIAMRolePublication(ctx, &rpc.DeleteIAMRolePublicationReq{
			EventType:   eventTypeDelete,
			Environment: envDelete,
			IamRoleArn:  iamRoleARNDelete,
		})
		if err != nil {
			log.Fatalf("Error deleting publication for service id (%s), event (%s), env (%s): %v", iamRoleARNDelete, eventTypeDelete, envDelete, err)
		}

		output.MapMsg("Deleted publication successfully", map[string]string{
			"Event Type":  eventTypeDelete,
			"Environment": envDelete,
			"IAM Role":    iamRoleARNDelete,
		})
	},
}
