package eventstream

import (
	"context"
	"log"

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

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

	"github.com/spf13/cobra"
)

type EventStreamResults struct {
	EventStreams []*rpc.EventStream
}

func (r EventStreamResults) AsTableData() [][]string {
	data := [][]string{}
	for _, event := range r.EventStreams {
		deprecated := "false"
		if event.Deprecated {
			deprecated = "true"
		}
		row := []string{event.EventType, event.Environment, event.RepoFilepath, deprecated}
		data = append(data, row)
	}
	return data
}

var listEventStreamsCommand = &cobra.Command{
	Use:   "list",
	Short: "List event streams",
	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.NewEventStreams(config)
		if err != nil {
			log.Fatal("Error creating event streams client: ", err.Error())
		}

		resp, err := c.List(ctx, &rpc.ListEventStreamsReq{})
		if err != nil {
			log.Fatal("Error fetching event stream: ", err.Error())
		}

		if err := output.Table([]string{"event type", "environment", "repo filepath", "deprecated"}, EventStreamResults{resp.GetEventStreams()}); err != nil {
			output.FatalError(err)
		}
		output.Newline()
	},
}
