using FastEndpoints; using FrameworkBLL.EIPConversation.EIPHandlers.EIPWebhook; using FrameworkDAL.DTO.MessageHub; using GB5Shared.DTO.Framework.Login; using GB5Shared.DTO.Framework.ResponseStandard; using GB5Shared.FastEndPoint; using System.Text.Json; using static GB5Shared.GB5Constant.Constant; namespace FrameworkSL.Endpoints.EIPConversation { public class RequestEIPConversation : BaseEndpoint> { private readonly IEIPWebhookBLL _eipWebhookBLL; private readonly ILogger _logger; public RequestEIPConversation( IEIPWebhookBLL eipWebhookBLL, ILogger logger) { _eipWebhookBLL = eipWebhookBLL; _logger = logger; } public override void Configure() { Post("/EIPConversation/RequestEIPConversation"); AllowAnonymous(); } public record MessageHubWebhookParameters( [property: FromHeader] string? Login, [property: FromBody] MessageHubWebhookDTO? MessageHubWebhookDTO ); protected override async Task> ExecuteAsync( MessageHubWebhookParameters req, LoginDTO loginDTO, CancellationToken ct) { try { // Log the bound DTO as raw payload for debugging _logger.LogInformation( "RAW WEBHOOK PAYLOAD: {Payload}", JsonSerializer.Serialize(req.MessageHubWebhookDTO)); // ✅ VALIDATION if (req?.MessageHubWebhookDTO == null) { _logger.LogWarning("Webhook received with null DTO."); return await GB5Shared.ResponseStandard.Response.CreateExceptionError( new ArgumentNullException(nameof(req.MessageHubWebhookDTO)), CacheKeyLevel.NOT_REQUIRED, loginDTO, "Invalid webhook payload", 400 ); } var messageCount = req.MessageHubWebhookDTO.Messages?.Count ?? 0; _logger.LogInformation( "WEBHOOK RECEIVED | LoginHeader={Login} | MessageCount={Count}", req.Login, messageCount ); // ✅ IMPORTANT: NO BUSINESS LOGIC HERE // Just forward to BLL await _eipWebhookBLL.HandleWebhookAsync( req.MessageHubWebhookDTO, loginDTO!, ct); _logger.LogInformation("WEBHOOK PROCESSING COMPLETED SUCCESSFULLY"); // ✅ Always return ACK (webhook providers expect fast response) return await GB5Shared.ResponseStandard.Response.CreateSuccessResponse( new { Status = "Webhook processed successfully" }, CacheKeyLevel.NOT_REQUIRED, loginDTO ); } catch (Exception ex) { _logger.LogError(ex, "WEBHOOK ERROR | LoginHeader={Login}", req?.Login ); return await GB5Shared.ResponseStandard.Response.CreateExceptionError( ex, CacheKeyLevel.NOT_REQUIRED, loginDTO, ex.Message, 500 ); } } } }