package configuration

import (
	"bytes"
	_ "embed"
	"log"
	"sync"

	"github.com/getsentry/sentry-go"
	"github.com/spf13/viper"
)

var (
	globalConfig Configuration
	globalLock   *sync.Mutex

	//go:embed fermentord.toml
	globalData []byte
)

func init() {
	globalLock = &sync.Mutex{}
}

func Global() Configuration {
	globalLock.Lock()
	defer globalLock.Unlock()

	return globalConfig
}

func Initialize() {
	setDefaults()
	viper.SetConfigName("fermentord")
	viper.SetConfigType("toml")
}

func LoadConfiguration() Configuration {
	globalLock.Lock()
	defer globalLock.Unlock()

	buf := bytes.NewBuffer(globalData)
	if err := viper.ReadConfig(buf); err != nil {
		panic(err)
	}

	if err := viper.MergeInConfig(); err != nil {
		log.Printf("Error loading configuration: %v", err)
	}

	config := Configuration{}
	if err := viper.Unmarshal(&config); err != nil {
		sentry.CaptureException(err)
		log.Fatal(err)
	}

	globalConfig = config

	return globalConfig
}
