using ChatMvc.LogConfig;
using ChatMvc.Managers;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authentication.MicrosoftAccount;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Options;
using Serilog;
using Serilog.Sinks.Grafana.Loki;
using Stripe;
using Stripe.Forwarding;
using System.Globalization;
using System.Security.Policy;

var builder = WebApplication.CreateBuilder(args);

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .Enrich.FromLogContext()
    .Enrich.WithProperty("app", "chat")
    .WriteTo.Console()
    .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog(); 

var config = builder.Configuration;

//builder.Services.AddAuthentication()
builder.Services.AddAuthentication(
options =>
 {
     options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
     options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = MicrosoftAccountDefaults.AuthenticationScheme;
 })
.AddCookie(options =>
{
    //options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
    //options.SlidingExpiration = true;
    options.AccessDeniedPath = "/Forbidden/";
    options.Cookie.Name = ".AspNet.SharedCookie";
    options.ExpireTimeSpan = TimeSpan.FromDays(30); // Define o tempo de expiração
    options.SlidingExpiration = true; // Renova o cookie a cada acesso
})
.AddGoogle(googleOptions =>
{
    googleOptions.ClientId = config.GetSection("Authentication:Google:ClientId").Value;
    googleOptions.ClientSecret = config.GetSection("Authentication:Google:ClientSecret").Value;
})
.AddMicrosoftAccount(microsoftOptions =>
{
    microsoftOptions.ClientId = config.GetSection("Microsoft_ClientId").Value;
    //microsoftOptions.ClientSecret = "2a7cb1bd-037a-49fa-9e5e-2b2655431af9"; 
    microsoftOptions.ClientSecret = config.GetSection("Microsoft_ClientSecret").Value;
});

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

builder.Services.AddMvc(options =>
    {
    options.Filters.Add(new RequireHttpsAttribute());
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
    })
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();
;

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("pt-BR"),
                new CultureInfo("en")
            };

    options.DefaultRequestCulture = new RequestCulture("pt-BR");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

StripeConfiguration.ApiKey = builder.Configuration["Stripe:SecretKey"];
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient();
builder.Services.AddSerilog();

builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-CSRF-TOKEN";
    options.Cookie.Name = "XSRF-TOKEN";
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});

builder.Services.AddScoped<TokenManager>();

var app = builder.Build();

var locOptions = app.Services.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);

app.UseMiddleware<RequestLocalizationMiddleware>();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    // Desabilita HTTPS redirection em desenvolvimento
    // app.UseHsts();
    // app.UseHttpsRedirection();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

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

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

app.UseSerilogRequestLogging();

app.UseRequestLocalization();

app.Run();
