package authfield

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/controlplane/infrastructure/rpc"
	"github.com/spf13/cobra"
)

var (
	eventTypeList, envList, msgList, fieldList string
)

func init() {
	listSubscriberGrantsCommand.Flags().StringVarP(&eventTypeList, "event-type", "t", "", "event type to list sub grants for")
	listSubscriberGrantsCommand.MarkFlagRequired("event-type")
	listSubscriberGrantsCommand.Flags().StringVarP(&envList, "environment", "e", "", "environment to list sub grants for")
	listSubscriberGrantsCommand.MarkFlagRequired("environment")
	listSubscriberGrantsCommand.Flags().StringVarP(&msgList, "message", "m", "", "message of authed field")
	listSubscriberGrantsCommand.MarkFlagRequired("message")
	listSubscriberGrantsCommand.Flags().StringVarP(&fieldList, "field", "f", "", "field of authed field")
	listSubscriberGrantsCommand.MarkFlagRequired("field")
}

type SubscriberGrantResults struct {
	SubscriberGrants []*rpc.AuthorizedFieldSubscriberGrant
}

func (r SubscriberGrantResults) AsTableData() [][]string {
	data := [][]string{}
	for _, grant := range r.SubscriberGrants {
		row := []string{grant.EventType, grant.IamRole, grant.Environment, grant.KmsGrantId, grant.AuthorizedField.MessageName, grant.AuthorizedField.FieldName}
		data = append(data, row)
	}
	return data
}

var listSubscriberGrantsCommand = &cobra.Command{
	Use:   "list-subscriber-grants",
	Short: "Lists subscriber grants based off of the auth context",
	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())
		}

		resp, err := c.ListAuthorizedFieldSubscriberGrantsByAuthorizedField(ctx, &rpc.ListAuthorizedFieldSubscriberGrantsByAuthorizedFieldReq{
			EventType:   eventTypeList,
			Environment: envList,
			AuthorizedField: &rpc.AuthorizedField{
				MessageName: msgList,
				FieldName:   fieldList,
			},
		})
		if err != nil {
			log.Fatal("Error fetching subscriber grants by auth context: ", err.Error())
		}

		if err := output.Table([]string{"event type", "iam role", "environment", "kms grant id", "message", "field"}, SubscriberGrantResults{resp.GetSubscriberGrants()}); err != nil {
			output.FatalError(err)
		}
		output.Newline()
	},
}
