using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Module.Tenancy.Extensions;

/// <summary>
/// 多租户服务注册及中间件扩展。
/// </summary>
public static class TenantServiceCollectionExtensions
{
    /// <summary>
    /// 注册租户上下文、解析中间件及默认租户提供者。
    /// </summary>
    public static IServiceCollection AddTenantResolution(this IServiceCollection services, IConfiguration configuration)
    {
        services.TryAddSingleton<ITenantContextAccessor, TenantContextAccessor>();
        services.TryAddScoped<ITenantProvider, TenantProvider>();
        services.TryAddScoped<ITenantCodeResolver, DatabaseTenantCodeResolver>();

        services.AddOptions<TenantResolutionOptions>()
            .Bind(configuration.GetSection("Tenancy"))
            .ValidateDataAnnotations();

        return services;
    }

    /// <summary>
    /// 使用多租户解析中间件。
    /// </summary>
    public static IApplicationBuilder UseTenantResolution(this IApplicationBuilder app)
        => app.UseMiddleware<TenantResolutionMiddleware>();
}
