using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;

namespace NexusReader.Maui.Infrastructure.Logging;

/// <summary>
/// Lightweight bridge service that intercepts logs, console outputs, and uncaught exceptions 
/// from the Blazor WebView/JS side, and routes them directly to Serilog under "BlazorWebView" context.
/// </summary>
public sealed class BlazorLoggingBridge
{
    private readonly ILogger _logger;

    public BlazorLoggingBridge(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger("BlazorWebView");
    }

    [JSInvokable("LogJsMessage")]
    public void LogJsMessage(string level, string message, string? stackTrace = null)
    {
        if (string.IsNullOrWhiteSpace(message))
        {
            return;
        }

        switch (level.ToLowerInvariant())
        {
            case "error":
            case "exception":
                if (!string.IsNullOrWhiteSpace(stackTrace))
                {
                    _logger.LogError("JS Unhandled Exception: {Message}\nStack Trace:\n{StackTrace}", message, stackTrace);
                }
                else
                {
                    _logger.LogError("JS Error: {Message}", message);
                }
                break;

            case "warning":
            case "warn":
                _logger.LogWarning("JS Warning: {Message}", message);
                break;

            case "info":
            case "log":
            default:
                _logger.LogInformation("JS Log: {Message}", message);
                break;
        }
    }
}
