package main

import (
	"os"
	"time"

	"github.com/kkyr/fig"
	"github.com/rs/zerolog"
)

type Config struct {
	Timezone string `fig:"tz" default:"America/New_York"`
	Server   struct {
		Port             string `fig:"port" default:"3000"`
		LocationPhotoDir string `fig:"locationPhotoDir" default:"./app/photos/locations/"`
	}
	Logger struct {
		Level       string `fig:"loglevel" default:"info"`
		LoggingFile string `fig:"loggingFile" default:"./app/log/goInventorize.log"`
	}
	Authentication struct {
		BasicAuth bool   `fig:"basicauth"`
		UserName  string `fig:"username" default:"admin"`
		Password  string `fig:"password" default:"password"`
	}

	Development bool `fig:"development"` // Cannot set default for BOOL will default to false if nothing supplied
}

func LoadConfig(s *Server) error {
	var cfg Config
	err := fig.Load(&cfg, fig.File("config.yaml"), fig.Dirs("./app/config"), fig.UseEnv("GI")) // Load in config.yaml, then overwrite with ENV variables prefixed with GI
	if err != nil {
		return err
	}
	logFile, err := os.OpenFile(cfg.Logger.LoggingFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) // Open/Create log file for writting to log
	if err != nil {
		return err
	}
	switch cfg.Logger.Level { // Setting our logging level
	case "error":
		zerolog.SetGlobalLevel(zerolog.ErrorLevel)
	case "warn":
		zerolog.SetGlobalLevel(zerolog.WarnLevel)
	case "debug":
		zerolog.SetGlobalLevel(zerolog.DebugLevel)
	default:
		zerolog.SetGlobalLevel(zerolog.InfoLevel)

	}
	loc, err := time.LoadLocation(cfg.Timezone) // Getting our timezone info from config
	if err != nil {
		return err
	}
	s.LogFile = logFile
	zerolog.TimestampFunc = func() time.Time { // Making sure our logger writes in the correct tz
		return time.Now().In(loc)
	}
	s.Log = zerolog.New(logFile).With().Timestamp().Logger()
	// Creating photo directory
	err = os.MkdirAll(cfg.Server.LocationPhotoDir, 0755)
	if err != nil {
		return err
	}

	s.Log.Info().Msg("Configuration loaded successfully...")
	s.Log.Debug().Msgf("%+v", cfg)
	s.Config = &cfg
	return nil
}
