using FrameworkBLL.EIPConversation.EIPHandlers.EIPFlowRepository; using GB5Shared.DTO.Framework.Login; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FrameworkBLL.EIPConversation.EIPHandlers.EIPEngine.TenantContext { public class TenantContext : ITenantContext { private readonly IHttpContextAccessor _httpContextAccessor; private readonly long? _overrideTenantId; private readonly ILogger _logger; public TenantContext(IHttpContextAccessor httpContextAccessor, ILogger logger, long? overrideTenantId = null) { _httpContextAccessor = httpContextAccessor; _overrideTenantId = overrideTenantId; _logger = logger; } public long TenantId { get { try { if (_overrideTenantId.HasValue) { _logger.LogInformation("Using override TenantId={TenantId}", _overrideTenantId.Value); return _overrideTenantId.Value; } var tenantClaim = _httpContextAccessor .HttpContext? .User? .FindFirst("TenantId")? .Value; if (string.IsNullOrWhiteSpace(tenantClaim)) { _logger.LogWarning("TenantId claim not found in HttpContext"); throw new UnauthorizedAccessException("TenantId claim not found."); } if (!long.TryParse(tenantClaim, out var tenantId)) { _logger.LogWarning("Invalid TenantId claim value: {TenantClaim}", tenantClaim); throw new UnauthorizedAccessException("Invalid TenantId claim."); } _logger.LogInformation("TenantId extracted from claim: {TenantId}", tenantId); return tenantId; } catch (System.Exception ex) { _logger.LogError(ex, "Error retrieving TenantId"); throw; } } } public LoginDTO LoginDTO { get { var tenantId = TenantId; if (tenantId > int.MaxValue || tenantId < int.MinValue) { _logger.LogError("TenantId {TenantId} exceeds Int32 range", tenantId); throw new OverflowException("TenantId exceeds Int32 range."); } var loginDto = new LoginDTO { ClientId = (int)tenantId }; _logger.LogInformation("LoginDTO created | ClientId={ClientId}", loginDto.ClientId); return loginDto; } } } }