// Configuration file to hold hardcoded configurations or extract from ENV

package configuration

import (
	"log"
	"os"

	"code.justin.tv/foundation/history-service/internal/common/config"
)

var (
	initialized = false
)

// Initialize the configurations with values from settings & ENV
func init() {
	if initialized {
		return
	}

	cfg, err := GetConfig()
	if err != nil {
		log.Fatal(err)
	}
	config.Register(cfg)

	err = config.Parse()
	if err != nil {
		log.Fatal(err)
	}

	initialized = true
}

// Resolve ...
func Resolve(field string) string {
	return config.Resolve(field)
}

// Environment Extract ENVIRONMENT variable or default to development
func Environment() (string, error) {
	environment := os.Getenv("ENVIRONMENT")

	if environment == "" {
		environment = "development"
	}

	return environment, nil
}

// GetConfig Get hardcoded config based on the environment
func GetConfig() (map[string]string, error) {
	environment, err := Environment()
	if err != nil {
		return nil, err
	}
	environmentConfigurations := map[string]map[string]string{
		"development": Development,
		"staging":     Staging,
		"prod":        Production,
	}

	configurations, ok := environmentConfigurations[environment]

	if !ok {
		log.Fatal("Environment: ", environment, " is not supported")
	}

	return configurations, nil
}
