package auth

import (
	"fmt"
	"sort"

	"github.com/spf13/cobra"
	"github.com/stephnangue/warden/cmd/helpers"
)

var ListCmd = &cobra.Command{
	Use:           "list",
	SilenceUsage:  true,
	SilenceErrors: true,
	Short:         "Lists the enabled auth methods on the Warden server",
	Long: `
Usage: warden auth list

  Lists the enabled auth methods on the Warden server. This command also
  outputs information about the enabled path including a
  human-friendly descriptions.

  List all enabled auth methods:

      $ warden auth list
`,
	RunE: runList,
}

func runList(cmd *cobra.Command, args []string) error {
	c, err := helpers.Client()
	if err != nil {
		return err
	}

	auths, err := c.Sys().ListAuth()
	if err != nil {
		return fmt.Errorf("error listing auth methods: %w", err)
	}

	if len(auths) == 0 {
		return helpers.RenderList(nil, func() {
			fmt.Println("No auth methods enabled")
		})
	}

	paths := make([]string, 0, len(auths))
	for path := range auths {
		paths = append(paths, path)
	}
	sort.Strings(paths)

	items := make([]map[string]any, 0, len(paths))
	for _, path := range paths {
		a := auths[path]
		items = append(items, map[string]any{
			"path":        path,
			"type":        a.Type,
			"accessor":    a.Accessor,
			"description": a.Description,
		})
	}

	return helpers.RenderList(items, func() {
		headers := []string{"Path", "Type", "Accessor", "Description"}
		data := make([][]any, 0, len(items))
		for _, m := range items {
			data = append(data, []any{m["path"], m["type"], m["accessor"], m["description"]})
		}
		helpers.PrintTable(headers, data)
	})
}
