using FrameworkDAL.DTO.MessageHub.MessageHubGenerator; using GB5Shared.DTO.Framework.Login; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace FrameworkBLL.MessageHub.MessageHubPlatforms { /// /// Telegram Platform implementation for MessageHub /// Handles sending both Template and Conversation messages /// public class TelegramPlatform : IMessageHubPlatform.ITelegramPlatform { private readonly IHttpClientFactory _httpClientFactory; private readonly MessageHubSettings _settings; private readonly ILogger _logger; public TelegramPlatform( IHttpClientFactory httpClientFactory, IOptions settings, ILogger logger) { _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); _settings = settings?.Value ?? throw new ArgumentNullException(nameof(settings)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } // ========================================================== // ✅ TEMPLATE MESSAGE // ========================================================== /// /// Sends a Telegram Template message via MessageHub /// public async Task SendTelegramTemplate( MessageHubDTO dto, LoginDTO login, CancellationToken ct) { if (dto == null) return Fail("Template DTO cannot be null"); if (login == null) return Fail("Login info missing"); var chatId = string.IsNullOrWhiteSpace(dto.Recipient) ? _settings.Telegram.DefaultRecipient : dto.Recipient; if (string.IsNullOrWhiteSpace(chatId)) return Fail("Telegram ChatId is missing"); var payload = new { chat_id = chatId, text = $"📢 TEMPLATE MESSAGE\n\n{dto.MessageText}\n\nSent by: {login.UserName}", parse_mode = "HTML" }; try { var client = _httpClientFactory.CreateClient(); var requestUrl = $"{(_settings.Telegram.BaseUrl ?? "https://api.telegram.org")}/bot{_settings.Telegram.BotToken}/sendMessage"; _logger.LogInformation( "Sending Telegram Template | ChatId={ChatId} | ActionId={ActionId}", chatId, dto.ActionId); var response = await client.PostAsync( requestUrl, new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"), ct); var responseContent = await response.Content.ReadAsStringAsync(ct); return new MessageHubResponseDTO { Success = response.IsSuccessStatusCode, Message = response.IsSuccessStatusCode ? "Telegram Template message sent successfully" : $"Telegram Template message failed: {response.StatusCode}", ResponseData = responseContent }; } catch (OperationCanceledException) { _logger.LogWarning("Telegram Template send cancelled | ChatId={ChatId}", chatId); return Fail("Telegram request cancelled"); } catch (Exception ex) { _logger.LogError(ex, "Telegram Template send failed | ChatId={ChatId}", chatId); return Fail($"Telegram error: {ex.Message}"); } } // ========================================================== // ✅ CONVERSATION MESSAGE // ========================================================== /// /// Sends a Telegram Conversation message via MessageHub /// public async Task SendTelegramConversation( MessageHubDTO dto, LoginDTO login, CancellationToken ct) { if (dto == null) return Fail("MessageHubDTO cannot be null"); if (login == null) return Fail("Login context is required"); if (string.IsNullOrWhiteSpace(_settings.Telegram.BotToken)) return Fail("Telegram BotToken is missing in configuration"); var chatId = !string.IsNullOrWhiteSpace(dto.Recipient) ? dto.Recipient : _settings.Telegram.DefaultRecipient; if (string.IsNullOrWhiteSpace(chatId)) return Fail("Telegram ChatId is missing"); var messageText = !string.IsNullOrWhiteSpace(dto.MessageText) ? dto.MessageText : dto.TextMessage; if (string.IsNullOrWhiteSpace(messageText) && string.IsNullOrWhiteSpace(dto.PayloadJson)) return Fail("Telegram message content is empty"); object payload; // Use pre-formed JSON payload if provided if (!string.IsNullOrWhiteSpace(dto.PayloadJson)) { payload = JsonConvert.DeserializeObject(dto.PayloadJson)!; } else { payload = new { chat_id = chatId, text = messageText, parse_mode = "HTML" }; } try { var client = _httpClientFactory.CreateClient(); var requestUrl = $"{(_settings.Telegram.BaseUrl ?? "https://api.telegram.org")}/bot{_settings.Telegram.BotToken}/sendMessage"; _logger.LogInformation( "Sending Telegram Conversation | ChatId={ChatId} | ActionId={ActionId}", chatId, dto.ActionId); var response = await client.PostAsync( requestUrl, new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"), ct); var responseContent = await response.Content.ReadAsStringAsync(ct); _logger.LogInformation( "Telegram response | Success={Success} | StatusCode={StatusCode} | ChatId={ChatId}", response.IsSuccessStatusCode, response.StatusCode, chatId); return new MessageHubResponseDTO { Success = response.IsSuccessStatusCode, Message = response.IsSuccessStatusCode ? "Telegram message sent successfully" : $"Telegram message failed: {response.StatusCode}", ResponseData = responseContent }; } catch (OperationCanceledException) { _logger.LogWarning("Telegram send cancelled | ChatId={ChatId}", chatId); return Fail("Telegram request cancelled"); } catch (Exception ex) { _logger.LogError(ex, "Telegram send failed | ChatId={ChatId}", chatId); return Fail($"Telegram error: {ex.Message}"); } } // ========================================================== // PRIVATE HELPER // ========================================================== private static MessageHubResponseDTO Fail(string reason) => new() { Success = false, Message = reason }; } }