using Elastic.CommonSchema.Serilog;
using FluentValidation;
using Microsoft.AspNetCore.HttpOverrides;
using PARR.API.Authentication;
using PARR.API.Installers;
using PARR.BLL;
using PARR.DAL;
using Serilog;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((context, config) =>
{
    if (context.HostingEnvironment.IsProduction())
        config.WriteTo.Console(new EcsTextFormatter());
    else
        config.WriteTo.Console();

    config.ReadFrom.Configuration(builder.Configuration);
});

// Add services to the container.
builder.Services.InstallDalServices(builder.Configuration);
builder.Services.InstallBllServices(builder.Configuration);
builder.Services.InstallApiServices(builder.Configuration);
builder.Services.InstallSettings(builder.Configuration);
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

// Dal configuration
builder.Configuration.AddDalConfigurations(builder.Services);
builder.Services.AddDallSettings(builder.Configuration);

// Auth
builder.Services.AddAuthentication(ParrAuthenticationOptions.DefaultScheme)
    .AddScheme<ParrAuthenticationOptions, ParrAuthenticationHandler>(ParrAuthenticationOptions.DefaultScheme, opt => { });
// не используем, так как проверка ролей остается прежней, а роли подставляем в ParrAuthenticationHandler
//builder.Services.AddSimpleRoleAuthorization<BaseSimpleRoleProvider>();

// При использовании балансировщика (haproxy, перенаправлять заголовки) (см ниже: app.UseForwardedHeaders();)
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;

    options.KnownNetworks.Clear();
    options.KnownProxies.Clear();
});


builder.Services.AddHttpContextAccessor();

builder.Services.AddControllers();
builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.InstallSwaggerService(builder.Configuration);

builder.Services.InstallCorsServices();


var app = builder.Build();

// При использовании балансировщика (haproxy, перенаправлять заголовки)
app.UseForwardedHeaders();

// Configure the HTTP request pipeline.
app.InstallSwagger();

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

app.MapControllers();

app.InstallCors(builder);
app.UseStaticFiles();

app.Run();
