package infra

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

// LoggerNew crea un Logger con nivel, destino y formato configurables.
// format debe ser "json" o "text". Si output es nil se usa os.Stderr.
// Retorna error si el formato no es valido.
func LoggerNew(level LogLevel, output io.Writer, format string) (*Logger, error) {
	if output == nil {
		output = os.Stderr
	}

	slogLevel := toSlogLevel(level)
	opts := &slog.HandlerOptions{Level: slogLevel}

	var handler slog.Handler
	switch format {
	case "json":
		handler = slog.NewJSONHandler(output, opts)
	case "text":
		handler = slog.NewTextHandler(output, opts)
	default:
		return nil, fmt.Errorf("logger_new: formato invalido %q, usa \"json\" o \"text\"", format)
	}

	return &Logger{
		Level:  level,
		Output: output,
		Format: format,
		Fields: map[string]any{},
		inner:  slog.New(handler),
	}, nil
}

// toSlogLevel convierte LogLevel a slog.Level.
func toSlogLevel(level LogLevel) slog.Level {
	switch level {
	case LogLevelDebug:
		return slog.LevelDebug
	case LogLevelInfo:
		return slog.LevelInfo
	case LogLevelWarn:
		return slog.LevelWarn
	case LogLevelError:
		return slog.LevelError
	default:
		return slog.LevelInfo
	}
}
