// Package app is a utility package
package app

import (
	"strings"

	"code.tnxs.net/work/lib/api/auth/auth_client"
	"code.tnxs.net/work/lib/app/logger"
	"github.com/spf13/viper"
	"github.com/taxnexus/go-force/force"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

// const dateTimeFormat = "2006-01-02T15:04:05-0800"
var sugar *zap.SugaredLogger
var config = Configuration{}
var appViper = viper.New()
var configured = false
var authClient = auth_client.Default
var authUser *User

// TheForce exports the salesforce interface
var TheForce *force.API

// InitConfig exports the config initialization func
func InitConfig(systemName string, initalLogLevel zapcore.Level) {
	if configured {
		return
	}
	sugar = logger.New(initalLogLevel)
	sugar.Infof("app.InitConfig: 📥 %s", systemName)
	appViper.SetConfigType("yaml")
	appViper.SetConfigName(systemName)
	appViper.AddConfigPath("/etc/work")
	appViper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	appViper.SetEnvPrefix("work")
	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
}
