using FJPSite.Data;
using FJPSite.Data.Identity;
using FJPSite.Enums;
using FJPSite.Factories;
using FJPSite.Factories.EntitySeeders;
using FJPSite.Helpers;
using FJPSite.Interfaces;
using FJPSite.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

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.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<UserEntity>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<RoleEntity>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddClaimsPrincipalFactory<UserClaimFactory>();
builder.Services.AddControllersWithViews();

builder.Services.AddTransient<UserClaimsPrincipalFactory<UserEntity, RoleEntity>, UserClaimFactory>();
builder.Services.AddScoped<IPermissionService, PermissionService>();
builder.Services.AddAuthorization(options =>
{
    foreach (FeatureEnum feature in Enum.GetValues(typeof(FeatureEnum)))
    {
        foreach (ActionEnum action in Enum.GetValues(typeof(ActionEnum)))
        {
            string policyName = $"Permission.{feature}.{action}";
            options.AddPolicy(policyName, policy =>
            policy.Requirements.Add(new PermissionRequirement(feature, action)));
        }
    }
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // 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.UseRouting();

app.UseAuthorization();

app.MapStaticAssets();

app.MapControllerRoute(
    name: "Admin",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

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

app.MapRazorPages()
   .WithStaticAssets();

app.Run();
