package eventstream

import (
	"context"
	"fmt"
	"log"

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

var (
	eventTypeDelete string
)

func init() {
	eventStreamDeleteByEventTypeCommand.Flags().StringVarP(&eventTypeDelete, "event-type", "t", "", "underlying event type for which to delete all event streams for")
	eventStreamDeleteByEventTypeCommand.MarkFlagRequired("event-type")
}

var eventStreamDeleteByEventTypeCommand = &cobra.Command{
	Use:   "delete-by-event-type",
	Short: "Deletes all event streams for a given event type",
	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 name you are removing", "delete", "event streams", []string{eventTypeDelete})
		if err != nil {
			log.Fatalf("Failed attempting a confirmation check: %v", err)
		} else if !passed {
			log.Fatal("Aborting due to confirmation failure")
		}

		resp, err := c.DeleteEventStreamsForEventType(ctx, &rpc.DeleteEventStreamsForEventTypeReq{EventType: eventTypeDelete})
		if err != nil {
			log.Fatal("Failed to delete event streams: ", err.Error())
		}

		if resp.Deleted {
			fmt.Printf("Successfully removed %d streams for %s!\n", resp.NumDeleted, eventTypeDelete)
		} else {
			fmt.Printf("Something bizarre happened... removal of %s unsuccessful (w/o error)", eventTypeDelete)
		}
	},
}
