using Asp.Versioning;
using Asp.Versioning.ApiExplorer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Web.Filters;
using TakeoutSaaS.Shared.Web.Security;
namespace TakeoutSaaS.Shared.Web.Extensions;

/// <summary>
/// Shared.Web 服务注册扩展。
/// </summary>
public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 注册控制器、模型验证、API 版本化等基础能力。
    /// </summary>
    public static IServiceCollection AddSharedWebCore(this IServiceCollection services)
    {
        // 1. 注册基础上下文与当前用户访问器
        services.AddHttpContextAccessor();
        services.AddEndpointsApiExplorer();
        services.AddScoped<ICurrentUserAccessor, HttpContextCurrentUserAccessor>();
        // 2. 注册控制器与全局过滤器
        services
            .AddControllers(options =>
            {
                options.Filters.Add<ValidateModelAttribute>();
                options.Filters.Add<ApiResponseResultFilter>();
            })
            .AddNewtonsoftJson();
        // 3. 配置模型验证行为
        services.Configure<ApiBehaviorOptions>(options =>
        {
            options.SuppressModelStateInvalidFilter = true;
        });
        // 4. 配置 API 版本化
        var apiVersioningBuilder = services.AddApiVersioning(options =>
        {
            options.AssumeDefaultVersionWhenUnspecified = true;
            options.DefaultApiVersion = new ApiVersion(1, 0);
            options.ReportApiVersions = true;
        });
        // 5. 注册版本化 Api Explorer
        apiVersioningBuilder.AddApiExplorer(setup =>
        {
            setup.GroupNameFormat = "'v'VVV";
            setup.SubstituteApiVersionInUrl = true;
        });
        // 6. 返回服务集合
        return services;
    }
}
