using CartWise.Application;
using CartWise.Infrastructure;
using CartWise.Infrastructure.Data;
using CartWise.Web.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);

builder.Services.AddScoped<IAuthorizationHandler, HouseholdMemberAuthorizationHandler>();
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("HouseholdMember", policy => policy.Requirements.Add(new HouseholdMemberRequirement()));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    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();
}
else
{
    // Local-first MVP: keep the SQLite schema current without a manual migration step.
    using var scope = app.Services.CreateScope();
    scope.ServiceProvider.GetRequiredService<CartWiseDbContext>().Database.Migrate();
}

app.UseHttpsRedirection();
app.UseRouting();

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

app.MapStaticAssets();

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


app.Run();

// Exposed so Microsoft.AspNetCore.Mvc.Testing (WebApplicationFactory<Program>) can bootstrap the app in tests.
public partial class Program;
