package cmd

import (
	"errors"
	"fmt"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/services/app"
	"github.com/dexidp/dex/storage"
	"github.com/spf13/cobra"
)

var appShowCmd = &cobra.Command{
	Use:   "show [app_id]",
	Short: "Display installed apps",
	Long: `Display the configuration for the apps.

Optional parameters:
- app-id: id of the application to display. If empty, display the list of available apps instead`,
	Args: cobra.MaximumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		s := utils.InitStorage(utils.InitConfig(""))

		if len(args) > 0 {
			showApp(args[0], app.New(s))
		} else {
			listApps(app.New(s))
		}
	},
}

func showApp(appID string, appService app.Service) {
	appConfig, err := appService.GetApp(appID)
	if err != nil {
		if errors.Is(err, storage.ErrNotFound) {
			utils.Failf("App with ID %s does not exist\n", appID)
		}
		utils.Failf("Failed to get config for app %s: %q\n", appID, err.Error())
	}

	fmt.Println("App config:")
	printProperty("Name", appConfig.Name, 1)
	printProperty("ID", appConfig.ID, 1)
	printProperty("Client secret", appConfig.Secret, 1)
	printProperty("Redirect URIs", "", 1)
	for _, uri := range appConfig.RedirectURIs {
		printProperty("", uri, 2)
	}
}

func listApps(appService app.Service) {
	apps, err := appService.ListApps()
	if err != nil {
		utils.Failf("Failed to list apps: %q\n", err.Error())
	}

	if len(apps) == 0 {
		fmt.Println("No app configured")
		return
	}
	for _, b := range apps {
		fmt.Printf("\t - %s: (%s)\n", b.ID, b.Name)
	}
}

func init() {
	appCmd.AddCommand(appShowCmd)
}
