using FrameworkDAL.DTO.EIPConversation; using FrameworkDAL.Query.EIPConversation.EIPConversationLog; using GB5Shared.DTO.Framework.Login; using GB5Shared.GenerateAutoNumber; using GB5Shared.QueryExecutor; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; using static GB5Shared.GB5Constant.Constant; namespace FrameworkDAL.CustomCode.EIPConversation.EIPConversationLog { public class EIPConversationLogDAL : IEIPConversationLogDAL { private readonly IQueryExecutor _qe; private readonly AutoNumber _autoNumber; private readonly ILogger _logger; public EIPConversationLogDAL(IQueryExecutor qe, AutoNumber autoNumber, ILogger logger) { _qe = qe ?? throw new ArgumentNullException(nameof(qe)); _autoNumber = autoNumber ?? throw new ArgumentNullException(nameof(autoNumber)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task GetOrCreateConversationAsync( int interactionSessionId, int tenantId, byte channelType, string sessionToken, LoginDTO loginDTO, CancellationToken ct = default) { try { var existing = await _qe.QuerySingleAsync( loginDTO, EIPConversationLogQB.GET_BY_INTERACTIONSESSIONID, new { InteractionSessionId = interactionSessionId }, cancellationToken: ct).ConfigureAwait(false); if (existing is not null) { await _qe.ExecuteAsync( loginDTO, EIPConversationLogQB.TOUCH_LAST_ACTIVITY, new { ConversationId = existing.ConversationId }, cancellationToken: ct).ConfigureAwait(false); return existing.ConversationId; } var auto = await _autoNumber.GetNumberAsync(1, AUTONUMBERCONSTANT.EIPCONVERSATION, loginDTO) .ConfigureAwait(false); await _qe.ExecuteAsync( loginDTO, EIPConversationLogQB.INSERT_HEADER, new { ConversationId = auto.StartNumber, TenantId = tenantId, InteractionSessionId = interactionSessionId, ChannelType = channelType, SessionToken = sessionToken, CreatedById = loginDTO.UserId, ModifiedById = loginDTO.UserId }, cancellationToken: ct).ConfigureAwait(false); return auto.StartNumber; } catch (Exception ex) { _logger.LogError(ex, "Failed to get-or-create conversation | InteractionSessionId={Id}", interactionSessionId); throw; } } public async Task InsertDetailAsync( int conversationId, byte direction, string message, LoginDTO loginDTO, CancellationToken ct = default) { try { var auto = await _autoNumber.GetNumberAsync(1, AUTONUMBERCONSTANT.EIPCONVERSATIONDETAIL, loginDTO) .ConfigureAwait(false); await _qe.ExecuteAsync( loginDTO, EIPConversationLogQB.INSERT_DETAIL, new { ConversationDetailId = auto.StartNumber, ConversationId = conversationId, Direction = direction, Message = message ?? string.Empty }, cancellationToken: ct).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Failed to insert conversation detail | ConversationId={Id}", conversationId); throw; } } } }