package logger

import (
	"fmt"
	"log/slog"
	"os"

	"gitea.computernetthings.ru/yash/crypto_alert_bot/internal/config"

	prettyLogger "github.com/charmbracelet/log"
)

var levelAdapter = map[string]slog.Level{
	"debug": slog.LevelDebug,
	"info":  slog.LevelInfo,
	"warn":  slog.LevelWarn,
	"error": slog.LevelError,
}

const (
	encodingConsole = "console"
	encodingJSON    = "json"
)

const (
	serviceNameKey = "service_name"
)

func NewAppLogger(cfg *config.Logger) *slog.Logger {
	var log *slog.Logger
	// select log level
	level, ok := levelAdapter[cfg.Level]
	if !ok {
		panic(fmt.Errorf("logger level not correct: %s", level))
	}
	// make handler
	switch cfg.Encoding {
	case encodingConsole:
		handler := prettyLogger.NewWithOptions(os.Stdout, prettyLogger.Options{
			Level:           prettyLogger.Level(level),
			ReportTimestamp: true,
			ReportCaller:    true,
		})
		log = slog.New(handler)
	case encodingJSON:
		handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level})
		log = slog.New(handler)
	default:
		panic(fmt.Errorf("logger encoding is not correct: %s", cfg.Encoding))
	}
	// add field with service name
	log = log.With(serviceNameKey, cfg.ServiceName)

	return log
}
