using Microsoft.Extensions.Caching.Memory;
using System.Diagnostics;
using System.Security.Claims;
using WorkFlowCheck.Common.Constants;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.Common.RequestContext;

namespace WorkFlowCheck.API.RequestContext
{
    public class HttpRequestContext : IRequestContext
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IMemoryCache _memoryCache;

        public HttpRequestContext(IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache)
        {
            _httpContextAccessor = httpContextAccessor;
            _memoryCache = memoryCache;

            TraceId = Activity.Current?.Id;
        }

        public string TraceId { get; }

        public int? CurrentUserId => CurrentDbUser?.Id;

        

        public string CurrentUsername => CurrentHttpUser?.Identity.Name;
        public string CurrentUserEmail => CurrentHttpUser?.FindFirst(System.Security.Claims.ClaimTypes.Email)?.Value;
        public CancellationToken RequestAborted => _httpContextAccessor.HttpContext.RequestAborted;

        private UserDTO CurrentDbUser => _memoryCache.Get<UserDTO>(MemoryCacheNames.UsersNamePrefix + CurrentUserEmail);

        private ClaimsPrincipal CurrentHttpUser => _httpContextAccessor.HttpContext.User;
    }
}
