using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using labdb.Models;

namespace labdb;

public static class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ??
                               throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
        builder.Services.AddDbContextFactory<AppDbContext>(options => options
            .UseNpgsql(connectionString, x => x
                .UseNetTopologySuite()
                .UseNodaTime()
            )
            .UseSnakeCaseNamingConvention()
            .UseAllCheckConstraints()
        );
        builder.Services.AddDatabaseDeveloperPageExceptionFilter();

        builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<AppDbContext>();
        builder.Services.AddRazorPages();

        var app = builder.Build();
        
        app.MigrateDatabase();

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Error"); // TODO: really use this?
        }

        app.UseStaticFiles();

        app.UseRouting();

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

        app.MapRazorPages();

        app.Run();
    }
    
    private static void MigrateDatabase(this WebApplication app)
    {
        var dbContextFactory = app.Services.GetRequiredService<IDbContextFactory<AppDbContext>>();
        using var dbContext = dbContextFactory.CreateDbContext();
        dbContext.Database.Migrate();
    }
}