using CSR.Infrastructure.Persistence;
using CSR.Infrastructure.Persistence.Repositories;
using CSR.Application.Services;
using CSR.Application.Interfaces;
using Microsoft.EntityFrameworkCore;
using Csr.Infrastructure.Persistence.Repositories;
using CSR.Infrastructure.Data;


var builder = WebApplication.CreateBuilder(args);

// Get configuration from appsettings.json, environment variables, and Docker secrets in that order
builder.Configuration
  .AddJsonFile("appsettings.json", optional: true)
  .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json", optional: true)
  .AddEnvironmentVariables()
  .AddKeyPerFile("/run/secrets", optional: true);


builder.Services.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
      options.LoginPath = "/Auth";
      options.LogoutPath = "/Logout";
      options.AccessDeniedPath = "/AccessDenied";
      options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
      options.SlidingExpiration = true;
    });
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"))
    .AddPolicy("UserOrAdmin", policy => policy.RequireRole("User", "Admin"));

// Add services to the container.
builder.Services.AddRazorPages();

// Set up connection to SQLite database
var dbPath = builder.Configuration["Database:Path"];
if (string.IsNullOrEmpty(dbPath))
{
  var folder = Environment.SpecialFolder.LocalApplicationData;
  var path = Environment.GetFolderPath(folder);
  dbPath = Path.Join(path, "csr.db");
}

builder.Services.AddDbContext<CSRDbContext>(options =>
{
  options.UseSqlite($"Data Source={dbPath}");
});

builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<Microsoft.AspNetCore.Identity.IPasswordHasher<CSR.Domain.Entities.User>, Microsoft.AspNetCore.Identity.PasswordHasher<CSR.Domain.Entities.User>>();
builder.Services.AddScoped<CSR.Domain.Interfaces.IPasswordHasher, CSR.Infrastructure.Services.PasswordHasherService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IUserRepository, UserRepository>();


var app = builder.Build();

// apply migrations and seed the database
using (var scope = app.Services.CreateScope())
{
  var services = scope.ServiceProvider;
  try
  {
    var context = services.GetRequiredService<CSRDbContext>();
    context.Database.Migrate();
    await DbInitializer.SeedDatabase(services);
  }
  catch (Exception ex)
  {
    var logger = services.GetRequiredService<ILogger<Program>>();
    logger.LogError(ex, "An error occurred while seeding the database");
  }
}

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
  app.UseExceptionHandler("/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.UseStaticFiles();

app.UseRouting();

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

app.MapRazorPages();

app.Run();
