using administration.Models;
using administration.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using static DBConnectionController;

namespace administration
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Charger les variables d'environnement depuis .env
            DotNetEnv.Env.Load();

            var builder = WebApplication.CreateBuilder(args);
            builder.Services.AddDbContext<FinancesContext>(options =>
                options.UseSqlServer(
                    Environment.GetEnvironmentVariable("ADMIN_DB_CONNECTION"),
                    sqlOptions => sqlOptions.EnableRetryOnFailure()
                )
            );

            AppSettings.Initialize(builder.Configuration);

            builder.Services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(300); // Durée d'expiration
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

            // Ajouter les services MVC
            builder.Services.AddControllersWithViews();

            builder.Services.AddHttpContextAccessor(); // obligatoire
            builder.Services.AddScoped<IUserSessionService, UserSessionService>();


            // Configurer la politique CORS pour autoriser l'accès depuis le frontend local
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowFrontend", policy =>
                {
                    policy.WithOrigins("http://localhost:5018")
                          .AllowAnyHeader()
                          .AllowAnyMethod();
                });
            });

            var app = builder.Build();

            // Configuration du pipeline HTTP
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseCors("AllowFrontend");
            app.UseSession();

            builder.Services.AddAuthentication("BasicAuthentication")
    .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);

            app.UseAuthentication();

            builder.Services.AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });
            // Route par défaut
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");


            app.Run();
        }
    }
}
