using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Radzen;
using TecniStamp.Components;
using TecniStamp.DependencyInjection;
using TecniStamp.Infrastructure.DAL.Context;
using TecniStamp.Service;
using TecniStamp.Service.Interfaces;
using TecniStamp.Service.Repository;

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddCascadingAuthenticationState();

builder.Services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireUppercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequiredLength = 1;        // puoi metterla anche a 1
    options.Password.RequiredUniqueChars = 0;
});

builder.Services.AddBusinessServices();

var connectionString = builder.Configuration.GetConnectionString("ConnectionString");
builder.Services.AddDbContext<TecniStampDbContext>(options =>
    options.UseSqlServer(connectionString)
);

builder.Services.AddScoped(typeof(ITecniStampGenericRepository<>), typeof(TecniStampGenericRepository<>));
builder.Services.AddScoped<ITecniStampUnitOfWork, TecniStampUnitOfWork>();
builder.Services.AddScoped<IManagerService, ManagerService>();

builder.Services.AddRadzenComponents();
builder.Services.AddHttpContextAccessor();

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Name = "auth_token";
        options.Cookie.MaxAge = TimeSpan.FromHours(8);
        options.LoginPath = "/account/login";
        options.LogoutPath = "/account/logout";
        options.AccessDeniedPath = "/access-denied";
    });
builder.Services.AddAuthorization();
builder.Services.AddCascadingAuthenticationState();

builder.Services.AddDbContext<TecniStampDbContext>(options =>
{
    options.UseSqlServer(connectionString);
});

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();
}

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

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

app.UseAntiforgery();

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

app.Use(async (context, func) =>
{
    try
    {
        await func();
    }
    catch (Exception e)
    {
        var logger = context.RequestServices.GetService<ILogger<Program>>();
        // Log dell'eccezione
        logger?.LogError(e, "Si è verificata un'eccezione durante l'elaborazione della richiesta.");

        context.Response.Clear();

        context.Response.StatusCode = e is BadHttpRequestException badHttpRequestException
            ? badHttpRequestException.StatusCode
            : 500;
    }
});

await app.RunAsync();
