using bdHerramientaCACOA.dbcontext;
using HerramientaCASA.Components;
using HerramientaCASA.Model;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using System.Globalization;
var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("es-ES");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("es-ES");

builder.Services.AddRazorPages()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
    });

// 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.AddBlazorBootstrap();
builder.Services.AddAntiforgery();
builder.Services.AddSingleton<UserState>();
builder.Services.AddScoped<ProtectedSessionStorage>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

// Inicializar las cadenas de conexión
var connectionStrings = builder.Configuration.GetSection("ConnectionStrings");
var writeConnectionString = connectionStrings["WriteConnection"];
var readOnlyConnectionString = connectionStrings["ReadOnlyConnection"];

if (string.IsNullOrEmpty(writeConnectionString) || string.IsNullOrEmpty(readOnlyConnectionString))
{
    throw new ArgumentNullException("Las cadenas de conexión no están configuradas correctamente.");
}

tsHerramientasCACOA.EstableceCBD(writeConnectionString, readOnlyConnectionString);

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;

    if (path == "/" ||
        path.StartsWithSegments("/_blazor") ||
        path.StartsWithSegments("/Content") ||
        path.StartsWithSegments("/Scripts") ||
        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?.idUser == 0)
    //{
    //    Console.WriteLine($"Redirigiendo al home desde: {path}");
    //    context.Response.Redirect("/");
    //    return;
    //}

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

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

app.Run();
