using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudGaming.Code.DataAccess.MultiTenantUtil;

/// <summary>
/// 多租户中间件
/// </summary>
public class MultiTenantTenantMiddleware
{
    private readonly RequestDelegate _next;
    public MultiTenantTenantMiddleware(RequestDelegate next)
    {
        _next = next;
    }


    /// <summary>
    /// 根据HttpContext获取并设置当前租户ID
    /// </summary>
    /// <param name="context"></param>
    /// <param name="_serviceProvider"></param>
    /// <param name="appConfig"></param>
    /// <returns></returns>
    public virtual async Task Invoke(HttpContext context,
        IServiceProvider _serviceProvider,
        AppConfig appConfig)
    {

        var host = context.Request.Host.Host;
        var app = AppConfigurationExtend.GetAppConfig(host);
        if (string.IsNullOrEmpty(appConfig.Identifier))
        {
            app.ToAppConfig(appConfig);
        }
        await _next.Invoke(context);
    }
}
