// Package app is a utility package
package app

import (
	"strings"

	"code.tnxs.net/taxnexus/lib/app/logger"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var sugar *zap.SugaredLogger
var config = Configuration{}
var appViper = viper.New()

// const dateTimeFormat = "2006-01-02T15:04:05-0800"

var configured = false

// InitConfig exports the config initialization func
func InitConfig(systemName string) {
	if configured {
		return
	}
	sugar = logger.New(zapcore.InfoLevel)
	sugar.Info("app.InitConfig: 📥 %s", systemName)
	appViper.SetConfigType("yaml")
	appViper.SetConfigName(systemName)
	appViper.AddConfigPath("/etc/taxnexus")
	appViper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	appViper.SetEnvPrefix("taxnexus")
	appViper.AutomaticEnv() // read in environment variables that match
	err := appViper.ReadInConfig()
	if err != nil {
		sugar.Fatalf("app.InitConfig: 💣 ⛔ can't read system config: %w", err)
	}
	err = appViper.Unmarshal(&config)
	if err != nil {
		sugar.Fatalf("app.InitConfig: 💣 ⛔ can't unmarshal system config: %w", err)
	}
	sugar = logger.New(GetLogLevel())
	sugar.Debugf("app.InitConfig: 👍 📤 serviceAccounts: %d", len(config.ServiceAccounts))
	configured = true
}
