using Microsoft.EntityFrameworkCore;
using Aberwyn.Data;
using System.Text;
using System.Globalization;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Aberwyn.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
    .AddEnvironmentVariables()
    .Build();
Console.WriteLine("📦 DEBUG: laddad raw-connectionstring: " + config.GetConnectionString("DefaultConnection"));

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args = args,
    EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"
});
builder.Configuration.AddConfiguration(config);
Console.WriteLine("🌍 Miljö: " + builder.Environment.EnvironmentName);
Console.WriteLine("🔗 Connection string: " + builder.Configuration.GetConnectionString("DefaultConnection"));


// Add services to the container.
builder.Services.AddControllersWithViews()
    .AddJsonOptions(opts =>
    {
        // Beh�ll propertynamn som i C#-klassen (PascalCase)
        opts.JsonSerializerOptions.PropertyNamingPolicy = null;
        // Ignorera null-v�rden vid serialisering
        opts.JsonSerializerOptions.IgnoreNullValues = true;
    });
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(1);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

builder.Services.AddRazorPages();
builder.Services.AddHttpClient();

// Configure your DbContext with MySQLs
Console.WriteLine("🔗 Connection string: " + builder.Configuration.GetConnectionString("DefaultConnection"));

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseMySql(
        builder.Configuration.GetConnectionString("DefaultConnection"),
        new MySqlServerVersion(new Version(8, 0, 36)),
        mySqlOptions => mySqlOptions.EnableRetryOnFailure()
    )
);


builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    options.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
builder.Services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequiredLength = 6;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = false;
});

builder.Services.AddControllersWithViews();
// Register your services
builder.Services.AddScoped<MenuService>();

builder.Services.AddSingleton<PushNotificationService>(sp =>
{
    var config = sp.GetRequiredService<IConfiguration>();
    return new PushNotificationService(
        config["VapidKeys:Subject"],
        config["VapidKeys:PublicKey"],
        config["VapidKeys:PrivateKey"]
    );
});

builder.Services.Configure<VapidOptions>(builder.Configuration.GetSection("Vapid"));
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Identity/Account/Login"; // korrekt för ditt nuvarande upplägg
});
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[] { new CultureInfo("sv-SE") };
    options.DefaultRequestCulture = new RequestCulture("sv-SE");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

//builder.Configuration
//    .SetBasePath(Directory.GetCurrentDirectory())
//    .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
//    .AddEnvironmentVariables();
builder.Services.AddSingleton<PushNotificationService>(sp =>
{
    var config = sp.GetRequiredService<IConfiguration>();
    return new PushNotificationService(
        config["VapidKeys:Subject"],
        config["VapidKeys:PublicKey"],
        config["VapidKeys:PrivateKey"]
    );
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();;
app.UseAuthorization();

// Map controller endpoints (including AJAX JSON actions)
app.MapControllers();

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

// Map Razor Pages
app.MapRazorPages();
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    var context = services.GetRequiredService<ApplicationDbContext>();
    // Vänta tills databasen är redo
    int retries = 10;
    while (retries > 0)
    {
        try
        {
            context.Database.OpenConnection(); // bara testa öppna anslutningen
            context.Database.CloseConnection();
            break; // lyckades!
        }
        catch
        {
            retries--;
            Console.WriteLine("⏳ Väntar på databas...");
            Thread.Sleep(3000);
        }
    }

    // Kör alla EF-migrationer automatiskt
    context.Database.Migrate();

    // Skapa standardroller och admin
    await IdentityDataInitializer.SeedData(services);

    // (valfritt) Lägg in exempelbudgetdata
    // await TestDataSeeder.SeedBudget(context);
}




app.Run();
