package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var log *zap.SugaredLogger

func Init(level string) error {
	var zapLevel zapcore.Level
	if err := zapLevel.UnmarshalText([]byte(level)); err != nil {
		zapLevel = zapcore.InfoLevel
	}

	cfg := zap.Config{
		Level:            zap.NewAtomicLevelAt(zapLevel),
		Encoding:         "console",
		EncoderConfig:    zap.NewDevelopmentEncoderConfig(),
		OutputPaths:      []string{"stdout"},
		ErrorOutputPaths: []string{"stderr"},
	}

	l, err := cfg.Build(zap.AddCallerSkip(1))
	if err != nil {
		return err
	}

	log = l.Sugar()
	return nil
}

func Info(msg string, keysAndValues ...interface{})  { log.Infow(msg, keysAndValues...) }
func Warn(msg string, keysAndValues ...interface{})  { log.Warnw(msg, keysAndValues...) }
func Error(msg string, keysAndValues ...interface{}) { log.Errorw(msg, keysAndValues...) }
func Debug(msg string, keysAndValues ...interface{}) { log.Debugw(msg, keysAndValues...) }
func Fatal(msg string, keysAndValues ...interface{}) { log.Fatalw(msg, keysAndValues...) }

func Sync() {
	if log != nil {
		_ = log.Sync()
	}
}
