package cmd

import (
	"context"
	"fmt"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/model"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/logger"
	"github.com/google/uuid"
	"github.com/spf13/cobra"
)

var (
	backendID           string
	backendName         string
	backendIssuer       string
	backendClientID     string
	backendClientSecret string
)

var backendAddCmd = &cobra.Command{
	Use:   "add",
	Short: "Add a new backend to the storage",
	Long: `Add a new backend to the storage.

Parameters to provide:
- id: Unique ID to represent the backend in the storage
- name: Human readable name to represent the backend. It will be used by
	the user in the authentication page to select a backend during
	authentication
- issuer: Full hostname of the OIDC provider, e.g. 'https://github.com'
- client-id: OIDC Client ID for the backend
- client-secret OIDC Client secret for the backend`,
	Run: func(cmd *cobra.Command, args []string) {
		addNewBackend()
	},
}

func addNewBackend() {
	c := utils.InitConfig("")
	logger.Init(c.LogLevel)

	s, err := db.New(*c)
	if err != nil {
		utils.Failf("failed to init storage: %s", err.Error())
	}

	if backendClientID == "" {
		utils.Fail("Empty client ID")
	}
	if backendClientSecret == "" {
		utils.Fail("Empty client secret")
	}

	backendIDUUID := uuid.New()

	backendConf := model.Backend{
		ID:   backendIDUUID,
		Name: backendName,
		Config: model.BackendOIDCConfig{
			ClientID:     backendClientID,
			ClientSecret: backendClientSecret,
			Issuer:       backendIssuer,
			RedirectURI:  c.RedirectURI(),
		},
	}
	if err := s.BackendStorage().AddBackend(context.Background(), &backendConf); err != nil {
		utils.Failf("Failed to add new backend to storage: %s", err.Error())
	}

	fmt.Printf("New backend %s added.\n", backendName)
}

func init() {
	backendCmd.AddCommand(backendAddCmd)

	backendAddCmd.Flags().StringVarP(&backendID, "id", "i", "", "ID to identify the backend in the storage")
	backendAddCmd.Flags().StringVarP(&backendName, "name", "n", "", "Name to represent the backend")
	backendAddCmd.Flags().StringVarP(&backendIssuer, "issuer", "d", "", "Full hostname of the backend")
	backendAddCmd.Flags().StringVarP(&backendClientID, "client-id", "", "", "OIDC Client ID for the backend")
	backendAddCmd.Flags().StringVarP(&backendClientSecret, "client-secret", "", "", "OIDC Client secret for the backend")
}
