package authfield

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 (
	envDelete, eventTypeDelete, msgDelete, fieldDelete string
)

func init() {
	authFieldDeleteCommand.Flags().StringVarP(&envDelete, "environment", "e", "staging", "environment for which to delete field")
	authFieldDeleteCommand.MarkFlagRequired("environment")
	authFieldDeleteCommand.Flags().StringVarP(&eventTypeDelete, "event-type", "t", "", "event type for which auth field will be removed for")
	authFieldDeleteCommand.MarkFlagRequired("event-type")
	authFieldDeleteCommand.Flags().StringVarP(&msgDelete, "message", "m", "", "message of auth field to delete")
	authFieldDeleteCommand.MarkFlagRequired("message")
	authFieldDeleteCommand.Flags().StringVarP(&fieldDelete, "field", "f", "", "field of auth field to delete")
	authFieldDeleteCommand.MarkFlagRequired("field")
}

var authFieldDeleteCommand = &cobra.Command{
	Use:   "delete",
	Short: "Deletes an authorized field",
	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 message or field you are removing", "delete", "authorized field", []string{msgDelete, fieldDelete})
		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.DeleteAuthorizedField(ctx, &rpc.DeleteAuthorizedFieldReq{
			EventType:   eventTypeDelete,
			Environment: envDelete,
			AuthorizedField: &rpc.AuthorizedField{
				MessageName: msgDelete,
				FieldName:   fieldDelete,
			},
		})
		if err != nil {
			log.Fatalf("Failed deletion of authorized field: %v", err)
		}

		if resp.Deleted {
			fmt.Printf("Successfully deleted authorized field (msg: %s) (field: %s)\n", msgDelete, fieldDelete)
		} else {
			fmt.Println("Unsuccessful removal (w/o error)")
		}
	},
}
