namespace Logger;

/// <summary>
/// Logger implementation that writes to console
/// </summary>
public class ConsoleLogger : ILogger
{
    private readonly LogLevel _minimumLevel;

    public ConsoleLogger(LogLevel minimumLevel = LogLevel.Trace)
    {
        _minimumLevel = minimumLevel;
    }

    public void Trace(string message) => Log(LogLevel.Trace, message);
    public void Debug(string message) => Log(LogLevel.Debug, message);
    public void Info(string message) => Log(LogLevel.Info, message);
    public void Warning(string message) => Log(LogLevel.Warning, message);
    public void Error(string message) => Log(LogLevel.Error, message);
    public void Fatal(string message) => Log(LogLevel.Fatal, message);

    public void Log(LogLevel level, string message)
    {
        if (level < _minimumLevel)
            return;

        var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
        var formattedMessage = $"[{timestamp}] [{level}] {message}";

        var previousColor = Console.ForegroundColor;
        try
        {
            Console.ForegroundColor = GetColorForLevel(level);
            Console.WriteLine(formattedMessage);
        }
        finally
        {
            Console.ForegroundColor = previousColor;
        }
    }

    private static ConsoleColor GetColorForLevel(LogLevel level)
    {
        return level switch
        {
            LogLevel.Trace => ConsoleColor.Gray,
            LogLevel.Debug => ConsoleColor.Cyan,
            LogLevel.Info => ConsoleColor.Green,
            LogLevel.Warning => ConsoleColor.Yellow,
            LogLevel.Error => ConsoleColor.Red,
            LogLevel.Fatal => ConsoleColor.Magenta,
            _ => ConsoleColor.White
        };
    }
}
