
using Microsoft.AspNetCore.Authentication.Cookies;
using GestionPersonalWeb.Components;
using GestionPersonalWeb.Models;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);


// Configurar servicios
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();
builder.Services.AddHttpClient("DefaultClient", client =>
{
    client.BaseAddress = new Uri(Utilidades.urlSwagger());
});
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.LoginPath = "/home";
    options.AccessDeniedPath = "/AccessDenied";
});
// Necesario para ver porqué está fallando ciertas cosas que dan el error Circuit
builder.Services.AddServerSideBlazor().AddCircuitOptions(option => { option.DetailedErrors = true; });
builder.Services.AddHttpContextAccessor();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(1);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

builder.Services.AddHttpClient("CertClient").ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler
    {
        ClientCertificateOptions = ClientCertificateOption.Manual // Forzar la selección del certificado
    };
});





builder.Services.AddBlazorBootstrap();
builder.Services.AddAntiforgery();
builder.Services.AddSingleton<UserState>();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();

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


app.UseAntiforgery();

app.Use(async (context, next) =>
{
    var userState = context.RequestServices.GetService<UserState>();
    var path = context.Request.Path;

    // Permitir solicitudes internas y recursos necesarios
    if (path == "/" ||
        path.StartsWithSegments("/_blazor") ||
        path.StartsWithSegments("/Content") ||
        path.StartsWithSegments("/Scripts") ||
        path.StartsWithSegments("/js") ||
        path.StartsWithSegments("/favicon.ico") ||
        path.StartsWithSegments("/_framework"))
    {
        await next();
        return;
    }

    // Redirigir al home si no hay token y la ruta no es pública
    if (userState?.Token == null)
    {
        Console.WriteLine($"Redirigiendo al home desde: {path}");
        context.Response.Redirect("/");
        return;
    }

    // Continuar con la solicitud
    await next();
});



app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();
