package recipe

import (
	"fmt"
	"sort"
	"strconv"
	"strings"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/spf13/cobra"
)

var RecipeListCommand = &cobra.Command{
	Use:     "list",
	Short:   "List recipes",
	Aliases: []string{"ls"},
	Args:    cobra.NoArgs,
	Run: func(cmd *cobra.Command, args []string) {
		catl, err := recipe.ReadRecipeCatalogue(internal.Offline)
		if err != nil {
			log.Fatal(err)
		}

		recipes := catl.Flatten()
		sort.Sort(recipe.ByRecipeName(recipes))

		table, err := formatter.CreateTable()
		if err != nil {
			log.Fatal(err)
		}

		headers := []string{
			"name",
			"category",
			"status",
			"healthcheck",
			"backups",
			"email",
			"tests",
			"SSO",
		}

		table.Headers(headers...)

		var rows [][]string
		for _, recipe := range recipes {
			row := []string{
				recipe.Name,
				recipe.Category,
				strconv.Itoa(recipe.Features.Status),
				recipe.Features.Healthcheck,
				recipe.Features.Backups,
				recipe.Features.Email,
				recipe.Features.Tests,
				recipe.Features.SSO,
			}

			if pattern != "" {
				if strings.Contains(recipe.Name, pattern) {
					table.Row(row...)
					rows = append(rows, row)
				}
			} else {
				table.Row(row...)
				rows = append(rows, row)
			}
		}

		if len(rows) > 0 {
			if internal.MachineReadable {
				out, err := formatter.ToJSON(headers, rows)
				if err != nil {
					log.Fatal("unable to render to JSON: %s", err)
				}
				fmt.Println(out)
				return
			}

			if err := formatter.PrintTable(table); err != nil {
				log.Fatal(err)
			}
		}
	},
}

var (
	pattern string
)

func init() {
	RecipeListCommand.Flags().BoolVarP(
		&internal.MachineReadable,
		"machine",
		"m",
		false,
		"print machine-readable output",
	)

	RecipeListCommand.Flags().StringVarP(
		&pattern,
		"pattern",
		"p",
		"",
		"filter by recipe",
	)
}
