package utils

import (
	"fmt"
	"os"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/services"
	"github.com/dexidp/dex/storage"
)

// Fail displays the given error to stderr and exits the program with a returncode 1
func Fail(errMsg string) {
	fmt.Fprintln(os.Stderr, errMsg)
	os.Exit(1)
}

// Fail displays the given formatted error to stderr and exits the program with a returncode 1
func Failf(msg string, args ...any) {
	fmt.Fprintf(os.Stderr, msg+"\n", args...)
	os.Exit(1)
}

// InitConfig inits the configuration, and fails the program if an error occurs
func InitConfig(configPath string) *config.AppConfig {
	conf, err := config.New(configPath)
	if err != nil {
		Failf("Failed to load the configuration: %s", err.Error())
	}
	return conf
}

// Initstorage inits the storage, and fails the program if an error occurs
func InitStorage(config *config.AppConfig) storage.Storage {
	s, err := services.InitStorage(config)
	if err != nil {
		Failf("Failed to init the storage: %s", err.Error())
	}
	return s
}
