using Serilog.Core;
using Serilog.Events;
using System.Net.Http;
using System.Text;
using System.Text.Json;

namespace QuantEngine.Web.Infrastructure
{
    public class TelegramSink : ILogEventSink
    {
        private readonly string _botToken;
        private readonly string _chatId;
        private static readonly HttpClient HttpClient = new HttpClient();

        public TelegramSink(string botToken, string chatId)
        {
            _botToken = botToken;
            _chatId = chatId;
        }

        public void Emit(LogEvent logEvent)
        {
            if (logEvent.Level >= LogEventLevel.Error)
            {
                var sb = new StringBuilder();
                sb.AppendLine("🚨 **QuantEngine Error Log**");
                sb.AppendLine($"• Timestamp: {logEvent.Timestamp:yyyy-MM-dd HH:mm:ss}");
                sb.AppendLine($"• Level: {logEvent.Level}");
                sb.AppendLine($"• Message: {logEvent.RenderMessage()}");

                if (logEvent.Exception != null)
                {
                    sb.AppendLine($"• Exception: {logEvent.Exception.Message}");
                }

                try
                {
                    var payload = new
                    {
                        chat_id = _chatId,
                        text = sb.ToString(),
                        parse_mode = "Markdown"
                    };
                    var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
                    
                    // Fire and forget to avoid blocking main execution threads
                    _ = HttpClient.PostAsync($"https://api.telegram.org/bot{_botToken}/sendMessage", content);
                }
                catch
                {
                    // Fallback to avoid crash loops inside logger
                }
            }
        }
    }
}
