package cmd

import (
	"context"
	"errors"
	"fmt"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db/backend"
	"github.com/dexidp/dex/storage"
	"github.com/spf13/cobra"
)

var backendShowCmd = &cobra.Command{
	Use:   "show [backend_id]",
	Short: "Display installed backends",
	Long: `Display the configuration for the backends.

Optional parameters:
- app-id: id of the backend to display. If empty, display the list of available backends instead`,
	Args: cobra.MaximumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		s, err := db.New(*utils.InitConfig(""))
		if err != nil {
			utils.Failf("Failed to init storage: %s", err.Error())
		}

		if len(args) > 0 {
			showBackend(args[0], s.BackendStorage())
		} else {
			listBackends(s.BackendStorage())
		}
	},
}

func showBackend(backendName string, backendService backend.BackendDB) {
	backendConfig, err := backendService.GetBackendByName(context.Background(), backendName)
	if err != nil {
		if errors.Is(err, storage.ErrNotFound) {
			utils.Failf("Backend with name %s does not exist\n", backendName)
		}
		utils.Failf("Failed to get config for backend %s: %q\n", backendName, err.Error())
	}

	fmt.Println("Backend config:")
	printProperty("ID", backendConfig.ID.String())
	printProperty("Name", backendConfig.Name)
	printProperty("Issuer", backendConfig.Config.Issuer)
	printProperty("Client ID", backendConfig.Config.ClientID)
	printProperty("Client secret", backendConfig.Config.ClientSecret)
	printProperty("Redirect URI", backendConfig.Config.RedirectURI)
}

func listBackends(backendStorage backend.BackendDB) {
	backends, err := backendStorage.GetAllBackends(context.Background())
	if err != nil {
		utils.Failf("Failed to list backends: %q\n", err.Error())
	}

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

func init() {
	backendCmd.AddCommand(backendShowCmd)
}
