using TakeoutSaaS.Shared.Abstractions.Tenancy;
namespace TakeoutSaaS.Module.Tenancy;
/// <summary>
/// 基于 <see cref="AsyncLocal{T}"/> 的租户上下文访问器，实现请求级别隔离。
/// </summary>
public sealed class TenantContextAccessor : ITenantContextAccessor
{
    private static readonly AsyncLocal<TenantContextHolder?> Holder = new();

    // 当前请求的租户上下文访问入口
    /// <summary>
    /// 获取或设置当前请求的租户上下文。
    /// </summary>
    public TenantContext? Current
    {
        get => Holder.Value?.Context;
        set
        {
            if (Holder.Value != null)
            {
                Holder.Value.Context = value;
            }
            else if (value != null)
            {
                Holder.Value = new TenantContextHolder { Context = value };
            }
        }
    }

    // 内部持有器用于绑定异步局部上下文
    private sealed class TenantContextHolder
    {
        public TenantContext? Context { get; set; }
    }
}
