using IdentityModel;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Security.Claims;
using Aurora.Infrastructure.Tenant;

namespace Aurora.Common.Tenant
{

    public class TenantContextProvider : ITenantContextProvider
    {
        readonly IHttpContextAccessor _httpContextAccessor;
        public TenantContextProvider(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public ITenantContext GetTenantContext()
        {
            TenantContext tenantContext = new();
            if (_httpContextAccessor.HttpContext == null) //cap
            {
                //todo
            }
            else if (_httpContextAccessor.HttpContext.User != null &&
                _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated) //external
            {
                ClaimsPrincipal claimsPrincipal = _httpContextAccessor.HttpContext.User;
                var subject = claimsPrincipal.Claims.FirstOrDefault(w => w.Type == JwtClaimTypes.Role);
                tenantContext.TenantCode = subject.Value;
            }
            else  //internal
            {
                tenantContext.TenantCode = _httpContextAccessor.HttpContext.Request.Headers[ConstString.CurrentTenantCode].FirstOrDefault();
                if (string.IsNullOrEmpty(tenantContext.TenantCode))
                {
                    tenantContext.TenantCode = "internal";
                }
            }

            return tenantContext;
        }

    }


}
