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 MultiTenantExtMiddleware
{
    private readonly RequestDelegate _next;
    public MultiTenantExtMiddleware(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)
    {
        AppConfig app = null;
        if (context.Request.Headers.TryGetValue("tenantId", out var str))
        {
            if (Guid.TryParse(str, out Guid tenantId))
            {
                app = AppConfigurationExtend.GetAppConfig(tenantId);
            }
        }
        if (app == null)
        {
            var host = context.Request.Host.Host;
            app = AppConfigurationExtend.GetAppConfig(host);
        }
        if (string.IsNullOrEmpty(appConfig.Identifier))
        {
            app.ToAppConfig(appConfig);
        }
        await _next.Invoke(context);
    }
}
