using StackExchange.Redis;
using Autofac.Core;

var builder = WebApplication.CreateBuilder(args);
var basePath = AppContext.BaseDirectory;
//���������ļ�
var _config = new ConfigurationBuilder()
                 .SetBasePath(basePath)
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 .Build();
builder.Services.AddSingleton(new AppSettingsHelper(_config));

// Add services to the container.
builder.Services.AddControllersWithViews();

#region redis

#endregion


#region �ӿڷ���
var groups = new List<Tuple<string, string>>
{
    //new Tuple<string, string>("Group1","����һ"),
    //new Tuple<string, string>("Group2","�����")
};
#endregion

#region ע�����ݿ�
builder.Services.AddScoped(options =>
{
    return new SqlSugarClient(new List<ConnectionConfig>()
    {
        new ConnectionConfig() { 
            ConfigId = DBEnum.OA2023DB, 
            ConnectionString = _config.GetConnectionString("OA2023DB"), 
            DbType = DbType.SqlServer, IsAutoCloseConnection = true }
    });
});
#endregion

#region ע��Swaggerע��(����)

if (AppSettingsHelper.Get("UseSwagger").ToBool())
{
    builder.Services.AddSwaggerGen(a =>
    {
        a.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "Api",
            Description = "Api�ӿ��ĵ�"
        });
        foreach (var item in groups)
        {
            a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}�ӿ��ĵ�" });
        }
        a.DocumentFilter<SwaggerApi>();
        a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
        a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
        a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            Description = "Value: Bearer {token}",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer"
        });
        a.AddSecurityRequirement(new OpenApiSecurityRequirement()
        {{
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
            }
        });
    });
}
#endregion

#region ����swaggerע��
//if (AppSettingsHelper.Get("UseSwagger").ToBool())
//{
//    builder.Services.AddSwaggerGen(c =>
//    {
//        c.SwaggerDoc("v1", new OpenApiInfo
//        {
//            Version = "v1",
//            Title = "�Ļ�����֧�����Խӿ�",
//            Description = "���ȴ�Auth��Ȩ=>login��ȡtoken������֤,����:token������֤(Bearer)"
//        });
//        c.DocumentFilter<SwaggerApi>();
//        var xmlPath = Path.Combine(basePath, "OASystem.API.xml");
//        c.IncludeXmlComments(xmlPath, true);
//        var xmlDomainPath = Path.Combine(basePath, "OASystem.Domain.xml");
//        c.IncludeXmlComments(xmlDomainPath, true);
//        c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
//        {
//            Description = "Value: Bearer {token}",
//            Name = "Authorization",
//            In = ParameterLocation.Header,
//            Type = SecuritySchemeType.ApiKey,
//            Scheme = "Bearer"
//        });
//        c.AddSecurityRequirement(new OpenApiSecurityRequirement()
//        {
//          {
//            new OpenApiSecurityScheme
//            {
//              Reference = new OpenApiReference
//              {
//                Type = ReferenceType.SecurityScheme,
//                Id = "Bearer"
//              },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
//            },new List<string>()
//          }
//        });
//    });
//}
#endregion

#region ������
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidAudience = "OASystem.com",
        ValidIssuer = "OASystem.com",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
    };
});
#endregion

#region ��ʼ����־
Log.Logger = new LoggerConfiguration()
       .MinimumLevel.Debug()
       .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
       .CreateLogger();
#endregion

#region ����ע��Autofac OASystem.Infrastructure��������Repository��β���ļ����ᱻע�뵽��Ŀ
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    try
    {
        var assemblyServices = Assembly.Load("OASystem.Infrastructure");
        builder.RegisterAssemblyTypes(assemblyServices).Where(a => a.Name.EndsWith("Repository")).AsSelf();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message + "\n" + ex.InnerException);
    }
});
#endregion

#region AutoMapper

AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
{
    cfg.AddProfile<_baseMappingProfile>();
});
builder.Services.AddSingleton(config);
builder.Services.AddScoped<IMapper, Mapper>();

#endregion

#region ��������
builder.Services.AddCors(c =>
{
    c.AddPolicy("AllowAllOrigins", policy =>
    {
        policy.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
    });
});
#endregion


var app = builder.Build();

app.UseCors("AllowAllOrigins");

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();


#region ����swaggerUI
if (AppSettingsHelper.Get("UseSwagger").ToBool())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
        foreach (var item in groups)
        {
            c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
        }
        c.RoutePrefix = string.Empty;
        c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
        c.DefaultModelsExpandDepth(-1);
    });
}
#endregion

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();