package log

import (
	"log/slog"
	"os"
	"proxy-server/gateway/env"
	"time"

	"github.com/lmittmann/tint"
	"github.com/mattn/go-colorable"
)

func Init() {
	var mode = env.AppLogMode
	var level = slog.LevelDebug
	if mode == "test" {
		level = slog.LevelInfo
	}

	switch mode {
	case "dev":
		writer := colorable.NewColorable(os.Stdout)
		logger := slog.New(tint.NewHandler(writer, &tint.Options{
			Level:      level,
			TimeFormat: time.RFC3339,
			ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
				err, ok := attr.Value.Any().(error)
				if ok {
					return tint.Err(err)
				}
				return attr
			},
		}))
		slog.SetDefault(logger)
	case "test":
		logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
			Level: level,
		}))
		slog.SetDefault(logger)
	default:
		panic("日志模式错误")
	}
}
