using Microsoft.AspNetCore.Http;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Shared.Web.Security;

/// <summary>
/// HttpContext 租户扩展方法。
/// </summary>
public static class TenantHttpContextExtensions
{
    /// <summary>
    /// 获取 HttpContext.Items 中缓存的租户上下文。
    /// </summary>
    /// <param name="context">当前 HttpContext</param>
    /// <returns>租户上下文，若不存在则返回 null</returns>
    public static TenantContext? GetTenantContext(this HttpContext? context)
    {
        if (context == null)
        {
            return null;
        }

        if (context.Items.TryGetValue(TenantConstants.HttpContextItemKey, out var value) &&
            value is TenantContext tenantContext)
        {
            return tenantContext;
        }

        return null;
    }
}
