using Microsoft.AspNetCore.Http;
using MultiTenancySample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MultiTenancySample
{
    public class TenantProvider : ITenantProvider
    {
        private readonly int _tenantId;

        public TenantProvider(IHttpContextAccessor accessor)
        {
            HttpContext httpContext = accessor.HttpContext;

            if (httpContext != null && httpContext.User.Identity.IsAuthenticated)
            {
                string tenantIdString = accessor.HttpContext.User.FindFirst("TenantId").Value;

                if (int.TryParse(tenantIdString, out int tenantId))
                {
                    _tenantId = tenantId;
                }
            }
        }

        public int GetTenantId()
        {
            return _tenantId;
        }
    }
}
