using Microsoft.Extensions.Logging;

namespace LazyBear.MCP.Services.Logging;

/// <summary>
/// ILoggerProvider, направляющий все логи в <see cref="InMemoryLogSink"/>.
/// </summary>
[ProviderAlias("InMemory")]
public sealed class InMemoryLoggerProvider(InMemoryLogSink sink) : ILoggerProvider
{
    public ILogger CreateLogger(string categoryName) =>
        new InMemoryLogger(sink, categoryName);

    public void Dispose() { }
}

internal sealed class InMemoryLogger(InMemoryLogSink sink, string category) : ILogger
{
    public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;

    public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;

    public void Log<TState>(
        LogLevel logLevel,
        EventId eventId,
        TState state,
        Exception? exception,
        Func<TState, Exception?, string> formatter)
    {
        if (!IsEnabled(logLevel)) return;

        var message = formatter(state, exception);
        var entry = new LogEntry(
            DateTimeOffset.Now,
            logLevel,
            category,
            message,
            exception?.ToString());

        sink.Add(entry);
    }
}
